Leetcode: 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?

第二遍做法:

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         int[] check = new int[32];
 4         int res = 0;
 5         for (int i=0; i<A.length; i++) {
 6             for (int j=0; j<32; j++) {
 7                 if ((A[i]>>j & 1) == 1) {
 8                     check[j]++;
 9                 }
10             }
11         }
12         for (int k=0; k<32; k++) {
13             if (check[k] % 3 != 0) {
14                 res |= 1<<k;
15             }
16         }
17         return res;
18     }
19 }

这个题比较直接的想法是用一个HashMap对于出现的元素进行统计,key是元素,value是出现个数,如果元素出现三次,则从HashMap中移除,最后在HashMap剩下来的元素就是我们要求的元素(因为其他元素都出现三次,有且仅有一个元素不是如此)。这样需要对数组进行一次扫描,所以时间复杂度是O(n),而需要一个哈希表来统计元素数量,总共有(n+2)/3个元素,所以空间复杂度是O((n+2)/3)=O(n)。这个方法非常容易实现,就不列举代码了。

在LeetCode的题目中要求我们不要用额外空间来实现,也就是O(1)空间复杂度。实现的思路是基于数组的元素是整数,我们通过统计整数的每一位来得到出现次数。我们知道如果每个元素重复出现三次,那么每一位出现1的次数也会是3的倍数,如果我们统计完对每一位进行取余3,那么结果中就只剩下那个出现一次的元素。总体只需要对数组进行一次线性扫描,统计完之后每一位进行取余3并且将位数字赋给结果整数,这是一个常量操作(因为整数的位数是固定32位),所以时间复杂度是O(n)。而空间复杂度需要一个32个元素的数组,也是固定的,因而空间复杂度是O(1)。这道题由于说了那个个数不为3的数个数是1,如果是2,4,5等等不为3的数的话还不能这么做

 1 public int singleNumber(int[] A) {
 2     int[] digits = new int[32];
 3     for(int i=0;i<32;i++)
 4     {
 5         for(int j=0;j<A.length;j++)
 6         {
 7             digits[i] += (A[j]>>i)&1;
 8         }
 9     }
10     int res = 0;
11     for(int i=0;i<32;i++)
12     {
13         res += (digits[i]%3)<<i;
14     }
15     return res;
16 }

naive方法,O(NlogN)注意那个single one的个数可能比3少,也可能比3多。所以想法就是先sorting,然后从小到大遍历每个元素,前后元素相同时counter++,不相同时看counter是否为3,不是的话就返回前一个元素,是的话counter重新置1.  特殊情况在于single one在最后,所以如果循环执行完了函数都还没有return,说明single one是最后的元素。要注意,对于这种需要返回值的function, 不能所有的return都在if语句里

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         java.util.Arrays.sort(A);
 4         int count = 1;
 5         int i;
 6         for (i = 1; i < A.length; i++) {
 7             if (A[i] == A[i-1]) {
 8                 count++;
 9             }
10             else {
11                 if (count != 3) return A[i-1];
12                 count = 1;
13             }
14         }
15         return A[i-1];
16     }
17 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/3798586.html