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?
class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int ret = 0;
for(int i = 0;i<n;i++)
ret ^= A[i];
return ret;
}
};
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?
如果整个数组中某bit上1出现的次数为 3*k +1 的话,那么只出现一次的数在该位必定为1。
class Solution {
public:
int singleNumber(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int ret = 0;
int mask = 0x0001;
for(int i = 0;i<32;i++)
{
int cnt = 0;
for(int j = 0;j<n;j++)
{
cnt += (A[j] & mask)>>i;
}
ret |= (cnt%3)<<i;
mask <<= 1;
}
return ret;
}
};
52 ms
本文介绍了一种线性时间复杂度的算法来找出数组中仅出现一次的元素,分别针对元素两次和三次重复的情况提供了两种实现方法,并且强调了不使用额外内存的重要性。
2355

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



