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?
Subscribe to see which companies asked this question
用异或做,很快很快。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int res=0;
for(int i = 0; i < nums.size(); i++){
res = res^nums[i];
}
return res;
}
};
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?
1.一个数组中有两个元素只出现一次,其他所有元素都出现两次,求这两个只出现一次的元素
[解题思路]
将数组所有元素都进行异或得到一个不为0的结果,根据这个结果中的不为0的某一位将数组分成两组
将两组中的元素进行异或,如两个数组的异或值都不为0,则得到最后结果
2.一个数组中有一个元素只出现1次,其他所有元素都出现k次,求这个只出现1次的元素
[解题思路]
当k为偶数时,同lss
但是这种做法需要对每个数字各位都访问一次。相对于简单版的”所有数字出现两次除了一个数字“题目中只用n次异或运算就解决的办法,还是过于冗杂了。
在discuss的解答中,使用了两个int整数表示状态以及位操作就完成了这种思路的全部计算。
-
%3运算只有三种状态:00,01,10,因此我们可以使用两个位来表示当前位%3。
-
对于每一位,我们让Two,One表示当前位的状态,B表示输入数字的对应位,Two+和One+表示输出状态。可以得到如下真值表
Two One B Two+ One+
0 0 0 0 0
0 0 1 0 1
0 1 0 0 1
0 1 1 1 0
1 0 0 1 0
1 0 1 0 0
1 1 0 X X (因为11状态不存在,可以忽略)
1 1 1 X X
经过化简后,可以得到如下表达式
One+ = (One ^ B) & (~Two)
Two+ = (~One+) & (Two ^ B)
当k为奇数时,将数组中每个元素的每一位相加mod k,得到结果即位出现1次的元素,时间复杂度O(nlen),空间复杂度为O(1)
69(1000101)出现1次, 33(100001)出现3次, 147(10010011)出现3次。
那么运算按二进制逐位求和并模k。
(
01000101+
00100001+
00100001+
00100001+
10010011+
10010011+
10010011
)mod(3) =
01000101(63)。
00100001+
00100001+
00100001+
10010011+
10010011+
10010011
等于31330137。每一位是1的个数。这已经不是二进制了。
最后的结果是31330137每一位mod(3),得到二进制表示01000101 = 十进制63
class Solution {
public:
int singleNumber(vector<int>& nums) {
int counterOne = 0;
int counterTwo = 0;
for (int i = 0; i < nums.size(); i++){
counterOne = (~counterTwo) & (counterOne ^ nums[i]);
counterTwo = (~counterOne) & (counterTwo ^ nums[i]);
}
return counterOne;
}
};