题目:
Given a non-empty 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?
Example 1:
Input: [2,2,1] Output: 1
Example 2:
Input: [4,1,2,1,2] Output: 4
代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
if(nums.size() == 1)
return nums[0];
int target = 0;
for(int i = 0; i<nums.size(); i++)
target ^= nums[i];
return target;
}
};
寻找唯一元素
本文介绍了一种线性时间复杂度的算法,用于从整数数组中找出只出现一次的元素,而其他元素都出现了两次。通过使用异或运算,该算法能够在不使用额外内存的情况下解决问题。示例包括输入数组[2,2,1]返回1,输入[4,1,2,1,2]返回4。
700

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



