问题描述
小M最近沉迷于一台神秘的弹子游戏机。游戏机每次会弹出一串数字序列,其中只有一个数字的弹子数量是奇数个,其余数字的弹子数量都是偶数个(即出现次数为偶数)。小M需要快速找出那个数量为奇数的数字,才能获得游戏奖励。你能帮助小M设计一个高效的算法来解决这个挑战吗?
要求:
- 设计一个算法,在 O(n) 的时间复杂度内找出那个独特的数字,其中 n 是数字序列的长度。
- 尽量减少额外空间的使用,以体现算法优化能力。
测试样例
样例1:
输入:
sequence = [5, 3, 5, 2, 3, 2, 7]输出:7解释:数字5出现2次(偶数次),数字3出现2次(偶数次),数字2出现2次(偶数次),数字7出现1次(奇数次)。
样例2:
输入:
sequence = [10, 10, 20, 30, 30, 40, 40]输出:20解释:数字10出现2次(偶数次),数字20出现1次(奇数次),数字30出现2次(偶数次),数字40出现2次(偶数次)。
样例3:
输入:
sequence = [1, 1, 2, 2, 3, 3, 4, 4, 5]输出:5解释:数字1出现2次(偶数次),数字2出现2次(偶数次),数字3出现2次(偶数次),数字4出现2次(偶数次),数字5出现1次(奇数次)。
约束条件
- 1 ≤ sequence.length ≤ 1001
- 0 ≤ sequencei ≤ 1000
- 序列长度为奇数
- 除了一个数字出现奇数次外,其余每个数字都出现偶数次
程序代码
#include <stdio.h>
int findUnique(int* sequence, int sequenceSize) {
int result = 0;
for (int i = 0; i < sequenceSize; i++) {
result ^= sequencei;
}
return result;
}
int main() {
int test1\[\] = {5, 3, 5, 2, 3, 2, 7};
int test2\[\] = {10, 10, 20, 30, 30, 40, 40};
int test3\[\] = {1, 1, 2, 2, 3, 3, 4, 4, 5};
printf("%d\n", findUnique(test1, 7)); // 7
printf("%d\n", findUnique(test2, 7)); // 20
printf("%d\n", findUnique(test3, 9)); // 5
return 0;
}
cpp
#include <stdio.h>
int findUnique(int* sequence, int sequenceSize) {
int result = 0;
for (int i = 0; i < sequenceSize; i++) {
result ^= sequence[i];
}
return result;
}
int main() {
int test1[] = {5, 3, 5, 2, 3, 2, 7};
int test2[] = {10, 10, 20, 30, 30, 40, 40};
int test3[] = {1, 1, 2, 2, 3, 3, 4, 4, 5};
printf("%d\n", findUnique(test1, 7)); // 7
printf("%d\n", findUnique(test2, 7)); // 20
printf("%d\n", findUnique(test3, 9)); // 5
return 0;
}
运行结果
