【LeetCode】Single Number II

来源:互联网 发布:乐器管子价格淘宝 编辑:程序博客网 时间:2024/06/07 02:45

Single Number II 
Total Accepted: 5359 Total Submissions: 17530 My Submissions
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?
【解题思路】
其实用额外的数组不太符合内存消耗比较少的要求,不过也AC了。
其中只有一个数出现了一次,其他都出现3次。
那么累计数组中的所有的数,int型为32位。
按位累计1出现的次数,那么每位1出现的次数应该是3的整数倍,如果那个出现一次的数在该位也为1,那么就记录一下。
最后按位累加就是结果。
Java AC

public class Solution {    public int singleNumber(int[] A) {        if(A == null || A.length == 0){            return 0;        }        int len = 32;        int count[] = new int[len];        for(int i = 0; i < len ; i++){            for(int j = 0; j < A.length ; j++){                count[i] += (A[j] >> i) & 1;                count[i] %= 3;            }        }        int result = 0;        for(int i = 0; i < len ; i++){            result += count[i] << i;        }        return result;    }}
0 0