Problem
Given an array of integers, every element appears twice except for one. Find that single one.
Solution
?可用嵌套循環(huán)暴力求解沽讹,時間復雜度為O(n2)踩娘。
?用異或運算巧解,時間復雜度為O(n)窗轩。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result = 0;
for (int i = 0; i < nums.size(); i++){
result ^= nums[i];
}
return result;
}
};
?原理:輸入數組 [4, 2, 4, 1, 2, 3, 3]
?運算等同于 (2 ^ 2) ^ (3 ^ 3) ^ (4 ^ 4) ^ 1 = 0 ^ 0 ^ 0 ^ 1 = 1