136. Single Number
Difficulty: Medium
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?
思路
元素与自身异或,结果为0。
vector中所有元素异或,由于除了一个元素只出现一次,其余元素都出现两次,计算结果为出现单次的元素。
代码
[C++]
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res = 0;
for(vector<int>::iterator it = nums.begin(); it != nums.end(); ++it)
res ^= *it;
return res;
}
};
本文介绍了一种使用异或运算解决数组中唯一单例问题的方法,该算法具备线性时间复杂度且无需额外内存。通过遍历整个数组并对每个元素进行异或操作,最终得到仅出现一次的元素。
314

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



