LeetCode: Single Number I & II

Given an array of integers, every element appears twice except for one. Find that single one.

这个方法重来没见过,以后估计也不会再见了。。

1 public static int singleNumber(int[] A) {
2         int sum = 0;
3         for (int a : A) {
4             sum ^= a;
5         }
6         return sum;
7     }

本以为不会再见了,不过看到第二个,觉得位操作还是有些应用的。。。。


Given an array of integers, every element appears three times except for one. Find that single one.

还是位操作,但和上面不能一样了。思路是,一个数如果出现了三次,那么这个数的每一位都会出现三次。那么我们可以统计下每一位一共出现多少次,再将这个数模3,剩下的数就是最后只出现一次的数。

具体实施时有两种方法:

1. 按照每一位的顺序进行统计。先统计第一位一共出现多少次,模3后记录下来,然后第二位。。。。。

 1 public int singleNumber(int[] A) {
 2         int result = 0;
 3         for (int i=0; i<32; i++) {
 4             int count = 0;
 5             for (int a : A) {
 6                 if (((a>>i)&1) == 1) 
 7                     count++;
 8             }
 9             result += (count%3)<<i;
10         }
11         return result;
12     }

 

2. 用三个整形数,one,two,three分别表示出现一次的有哪些位,出现两次的哪些,出现三次的。。。

最后one所代表的就是只出现一次的数。

再更新one,two,three的时候要注意顺序。首先要更新的是two。因为two等于上一次只出现一次的位 & 当前数字包含1的位。所以不能先更新one。

当three中某些位出现1时,把one和two中的相应的位清0。

 1 public int singleNumber(int[] A) {
 2         int one=0, two=0, three=0;
 3         for (int a : A) {
 4             two |= one & a;
 5             one ^= a;
 6             three = one & two;
 7             one &= ~three;
 8             two &= ~three;
 9         }
10         return one;
11     }

 

 

posted on 2014-01-19 11:31  longhorn  阅读(264)  评论(0编辑  收藏  举报

导航