Single Number
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?
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?
如果我自己想的话,大概想不出来这两道题该如何做,感觉自己还需要更宽广的思维...
这两道题的核心思想就是利用二进制的性质,将每一个数都拆成二进制位来计数.
Single Number
class Solution {
public:
int singleNumber(int A[], int n) {
int res = 0;
for(int i = 0; i < n; i++)
{
res ^= A[i];
}
return res;
}
};
Single Number II
class Solution {
public:
int singleNumber(int A[], int n) {
int bit[32];
for(int i = 0; i < 32; i++)
{
bit[i] = 0;
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < 32; j++)
{
bit[j] += (A[i] >> j) & 1;
}
}
int res = 0;
for(int i = 0; i < 32; i++)
{
bit[i] %= 3;
res += (bit[i] > 0 ? 1 : 0) << i;
}
return res;
}
};
本文介绍如何在数组中找出只出现一次的元素,对于两次和三次重复的情况提供了两种算法实现。通过位操作达到线性时间和常数空间复杂度的要求。
2353

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



