很经典的XOR的题了,XOR可以让相同的两位变成0,不同的两位变成1,所以这一题我们只需要XOR所有的数。Linear time,常数空间,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int singleNumber(vector<int>& nums) { | |
int res = 0; | |
for(auto& num : nums) | |
res ^= num; | |
return res; | |
} | |
}; |
No comments:
Post a Comment