Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
題目
給定一個整數(shù)數(shù)組,里面只有一個數(shù)只出現(xiàn)一次,其余的數(shù)都出現(xiàn)兩次,找出只出現(xiàn)一次的數(shù)。
方法
采用異或運算^
a ^ a = 0
a ^ 0 = a
a ^ b ^ c = a ^ (b ^ c)
c代碼
#include <assert.h>
int singleNumber(int* nums, int numsSize) {
int i = 0;
int single = 0;
for(i = 0; i < numsSize; i++) {
single ^= nums[i];
}
return single;
}
int main() {
int nums[5] = {1,3,3,1,5};
assert(singleNumber(nums, 5) == 5);
return 0;
}