[LeetCode] Single Number
阿新 • • 發佈:2017-07-10
could implement col algo public xtra arr com note
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?
給定一個數組,其中只有一個數字出現了1次,其他的數字都出現了2次。求出這個出現一次的數字。這道題利用XOR進行求解,如果兩個數字相同,那麽它們的XOR為0,然而0與任何數XOR都是任何數。所以用0與數組中各個數XOR,最後的結果就是那個只出現一次的數字。
class Solution { public: int singleNumber(vector<int>& nums) { int res = 0; for (int num : nums) res ^= num; return res; } }; // 13 ms
[LeetCode] Single Number