题目:
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) {
int result = 0;
for (auto c : nums)
result ^= c;
return result;
}
};
本文介绍了一种线性时间复杂度的算法,用于从整数数组中找出仅出现一次的元素,其余元素均出现两次。该算法巧妙地利用了异或运算的特性,无需额外内存开销。

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



