Given an array of integers, every element appears twice except for one. Find that single one.
给出一组数据,每个元素出现两次,除了一个元素之外,找到那个出现一次的元素。
思路:
a^b=b^a 所以 假设 把所有相同的先进行异或
然后 出现多个0 ;
0与 那单个元素异或 ;
则 最后 剩下来那个 就是 single one。
C++:
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) { 4 if(n==0||A==NULL) return 0; 5 6 int tmp=A[0]; 7 int i=0; 8 for(i=1;i<n;i++) 9 { 10 tmp=tmp^A[i]; 11 } 12 13 return tmp; 14 } 15 };
Python:
1 class Solution: 2 # @param A, a list of integer 3 # @return an integer 4 def singleNumber(self, A): 5 res=A[0] 6 for i in range(1,len(A)): 7 res=res^A[i] 8 return res
Python另一种方法:
1 class Solution: 2 def singleNumber(self, A): 3 dict = {} 4 for i in range(len(A)): 5 if A[i] not in dict: 6 dict[A[i]] = 1 7 else: 8 dict[A[i]] += 1 9 for word in dict: 10 if dict[word] == 1: 11 return word
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
将数转化为二进制的位,数出现了三次相当于其对应的二进制上每个位置出现了3次,这里有个抽象的地方就是,例如数中包含1,3两个其二进制的第一位都包含1,
怎么区分,其实并不需要区分,无论是数字3的还是数字1的二进制第一位的1都无所谓,因为我们完全可以将其认为总共是6次,无论先用的数字3的还是用的数字1的,
都能将该位置凑够两组重复了3次的1
考虑全部用二进制表示,如果我们把 第 ith 个位置上所有数字的和对3取余,那么只会有两个结果 0 或 1 (根据题意,3个0或3个1相加余数都为0). 因此取余的结果就是那个 “Single Number”.
1 int singleNumber(int A[], int n) { 2 int count[32] = {0}; 3 int result = 0; 4 for (int i = 0; i < 32; i++) { 5 for (int j = 0; j < n; j++) { 6 if ((A[j] >> i) & 1) { 7 count[i]++; 8 } 9 } 10 result |= ((count[i] % 3) << i); 11 } 12 return result; 13 }