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
解释:
数组中只有一个数字只出现了一次,其他数字则出现了两次,求出这个数字,用Counter()自然可以解,但是从这道题目学到的是奇技淫巧是位运算,将数组中的所有数字都异或一遍最后剩下的即为所求,因为数字和它本身异或的结果是0,任何数和0异或的结果是任何数,初始的值初始化为0,因为0和任何数异或不影响结果。
python代码:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x,y:x^y,nums)
c++代码:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n=0;
for (auto num:nums)
{
n^=num;
}
return n;
}
};
ps.合理使用set()函数和sum()函数来求这类题目:
python代码:
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return 2*sum(set(nums))-sum(nums)
结论:
学会使用位运算,这里学会了异或的特性。
学会使用python中的reduce()函数和lambda表达式。