只出現(xiàn)一次的數(shù)字
我們可以考慮 異或運算 ,它是滿足交換律和結合的,也就是說 abc = acb,這樣當我們遍歷數(shù)組,順次進行異或運算,那么最終的結果就是唯一的不重復數(shù)字。
Let us consider the above example.
Let ^ be xor operator as in C and C++.
//
//res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4
//
//Since XOR is associative and commutative, above
//expression can be written as:
//res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)
//= 7 ^ 0 ^ 0 ^ 0
//= 7 ^ 0
//= 7
執(zhí)行耗時 4ms, 戰(zhàn)勝100% 的提交
int singleNumber(int* nums, int numsSize) {
int result = nums[0];
for (int i = 1; i < numsSize; i++) {
result ^= nums[i];
}
return result;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
int arr[] = {1,1,2,3,2};
int a = singleNumber(arr, 5);
printf("%d\n",a);
}
return 0;
}