Single Number II

来源:互联网 发布:中铁一局集团网络学校 编辑:程序博客网 时间:2024/06/10 08:39

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?

Have you been asked this question in an interview?

做过single number i 之后,要掌握的不仅仅使xor 操作,更要掌握它的核心思想:找到如何可以消除出现n次的数

下面这种方法只是针对出现三次做的,当然 如果出现多次,则需要n个parameter 去记录出现了 i 次的位置
第一种方法第二次看的时候对于for 循环里
twos^=ones&A[i]
这一句不能理解为什么亦或。
原因:本身for 循环里面可以保证twos :0011; onces : 0100.
因为mod 3 过,所以twos 和onces 能够保证在相同的位上不会同时为1,即第一条语句不会出现某个位上出现了4次而不被考虑的情况
即不会出现情况:twos :0011,ones&A[i] = 0010 , 然后
twos^=ones&A[i] = 0011 ^ 0010 这种情况
所以
twos^=ones&A[i]
或者写成
twos|=ones&A[i]
都是可以的

public class Solution {    public int singleNumber(int[] A) {        if(A==null||A.length==0){return -1;}        int ones=A[0];//to record the position appear twice        int twos=0;// to record the position appear twice        int temp=0;// t record the position appear three times        for(int i=1;i<A.length;i++){            twos^=ones&A[i];            ones=ones^A[i];            temp=ones&twos;            ones=ones^temp;            twos=twos^temp;        }        return ones;    }}
<pre name="code" class="java">这种方法 则应用可以比较普遍,不管出现几次 只更改需要 mod 的数值即可
public class Solution {    public int singleNumber(int[] A) {        if (A == null || A.length == 0) {            return -1;        }        int result=0;        int[] bits=new int[32];        for (int i = 0; i < 32; i++) {            for(int j = 0; j < A.length; j++) {                bits[i] += A[j] >> i & 1;                bits[i] %= 3;            }            result |= (bits[i] << i);        }        return result;    }}


0 0
原创粉丝点击