Single Number
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?
解题思路
class Solution {
public:
int singleNumber(vector<int>& nums) {
if (nums.size() == 0) return 0;
int ans = nums[0];
for (int i = 1; i < nums.size(); ++i) {
ans ^= nums[i];
}
return ans;
}
};
本文介绍了一种线性时间复杂度的算法来找出数组中只出现一次的整数。该算法利用异或运算的特性,不使用额外内存即可实现。
279

被折叠的 条评论
为什么被折叠?



