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?
Difficulty:Easy
class Solution {
public:
int singleNumber(vector<int>& nums) {
int len = nums.size();
if(len==1)
return nums[0];
sort(nums.begin(),nums.end());
for(int i = 0;i<len;i=i+2)
{
if(i==len-1||nums[i]!=nums[i+1])
return nums[i];
}
}
};
Python中,^是位的异或运算,能很巧妙的把那个落单的数找出来
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for i in nums:
result = result^i
return result