Single Number通用解

来源:互联网 发布:dokuwiki nginx 编辑:程序博客网 时间:2024/06/06 04:55

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

当k=2的时候,很明显可以用异或解。因为:

A^B=B^A
A^B^B=A

所以当k>2的时候,受异或的启发,同样需要一种运算符,满足:

A#B=B#A
A#B#…#B=A

本质上,就是要维持一个长度为32的数组bit[],记录下对于array中的每一个数,每一位上1的出现次数。每出现k次,就把bit[i]重置为0,即实现了上面的#运算符。

public int singleNumber(int[] nums) {    int[] bit = new int[32];    for (int i = 0; i < 32; i++) {        bit[i] = 0;    }    for (int i = 0; i < nums.length; i++) {        int number = nums[i];        for (int j = 0; j < 32; j++) {            boolean hasBit = ((number & (1 << j)) != 0);            if (hasBit)                bit[j] = (bit[j] + 1) % 3;        }    }    int target = 0;    for (int i = 0; i < 32; i++) {        if (bit[i] > 0)            target = target | (1 << i);    }    return target;}
0 0