LeetCode 137 Single Number II
2014-03-04 22:38
330 查看
题目
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 如果可以使用额外的空间,考虑HashTable。
2 和single number 一样( http://blog.csdn.net/xift810/article/details/19772473 ),都要考虑底层,也就是从bit的角度来进行突破。可以发现 如果是 111 2,那么最后一位都3个1 ,倒数第二位是1个1;如果是 1113 那么最后一位是4个1,倒是第二位是2个1 。。。。可以发觉每一位
%3之后,得到的值要么是1,要么是0。因为只要出现过3次的,在相同位相加然后%3后,都自然为0。最后剩下的就是唯一出现过一次的那个数字的二进制表示。
3 这个方法可以应用到出现过任何次数的时候。
代码
思路2
另外看到一个特别有趣的方式,练32位数组都不用了
int sol2(int A[], int n)
{
int one = 0, two = 0, three = 0;
for (int i = 0;i < n;++i) {
two |= one & A[i]; 新的那个数和出现过一次(one) & 就是出现过两次,加到Two里面
one ^= A[i]; 和one ^ 如果没出现过,什么都不会发生;如果出现过,自然消失。
three = one & two; 如果出现第三次的必然是one 和 two的合并内容
one &= ~three; 把第三次出现的从one删除
two &= ~three; 把第三次出现的从two删除
}
return one;
}
我表示这个无法想到。。。
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 如果可以使用额外的空间,考虑HashTable。
2 和single number 一样( http://blog.csdn.net/xift810/article/details/19772473 ),都要考虑底层,也就是从bit的角度来进行突破。可以发现 如果是 111 2,那么最后一位都3个1 ,倒数第二位是1个1;如果是 1113 那么最后一位是4个1,倒是第二位是2个1 。。。。可以发觉每一位
%3之后,得到的值要么是1,要么是0。因为只要出现过3次的,在相同位相加然后%3后,都自然为0。最后剩下的就是唯一出现过一次的那个数字的二进制表示。
3 这个方法可以应用到出现过任何次数的时候。
代码
public class Solution { public int singleNumber(int[] A) { if(A.length==0){ return 0; } int[] record = new int[32]; for(int i=0;i<32;i++){ int cnt =0; for(int j=0;j<A.length;j++){ if(((A[j]>>i)&1)!=0){ cnt++; } } record[i]=cnt%3; } int ans=0; for(int i=0;i<32;i++){ ans|=(record[i]<<i); } return ans; } }
思路2
另外看到一个特别有趣的方式,练32位数组都不用了
int sol2(int A[], int n)
{
int one = 0, two = 0, three = 0;
for (int i = 0;i < n;++i) {
two |= one & A[i]; 新的那个数和出现过一次(one) & 就是出现过两次,加到Two里面
one ^= A[i]; 和one ^ 如果没出现过,什么都不会发生;如果出现过,自然消失。
three = one & two; 如果出现第三次的必然是one 和 two的合并内容
one &= ~three; 把第三次出现的从one删除
two &= ~three; 把第三次出现的从two删除
}
return one;
}
我表示这个无法想到。。。
相关文章推荐
- leetCode: Single Number II [137]
- LeetCode137——Single Number II
- leetcode 137 Single Number II
- leetcode 137 single NumberII “半加器状态转换”解法
- 【LeetCode】SingleNumberII_137
- LeetCode(137) Single Number II
- LeetCode 137: Single Number II
- leetcode: (137) Single Number II
- [LeetCode 137] Single Number II(位运算的巧妙运用初级篇)
- LeetCode 137 Single Number II
- 【LeetCode】(137)Single Number II(Medium)
- LeetCode 137 Single Number II
- leetcode 137: Single Number II
- Leetcode_137_Single Number II
- leetcode || 137、Single Number II
- leetcode文章137称号-Single Number II
- LeetCode(137)Single NumberII
- leetcode 137 Single Number II
- leetcode137 Single Number II
- Leetcode 137: (Single Number II)