數組中除一個元素外其他所有元素出現二或三次,找到只出現一次的元素

1、數組中除一個元素外其他所有元素出現二,找到只出現一次的那個元素。

public int singleNumber(int[] nums) {
        int res = nums[0];
        for (int i = 1; i < nums.length; i++)
            res = res ^ nums[i];

        return res;
    }

2、數組中除一個元素外其他所有元素出現三次,找到只出現一次的那個元素。

public static int singleNumber(int[] nums) {
    int len = nums.length, result = 0;
    for (int i = 0; i < 32; i++) {
        int sum = 0;
        for (int j = 0; j < len; j++) {
            sum += (nums[j] >> i) & 1;
        }
        result |= (sum % 3) << i;
    }
    return result;
    }

3、數組中所有元素出現兩次,其中有兩個元素只出現一次,找出這兩個元素。

 public static int[] geTwoEle(int[] res){
        if(res.length==2)return res;
        int []val=new int[2];
        int temp=res[0];
        for(int i=1;i<res.length;i++){
            temp^=res[i];
        }
        //find the leftmost pos where two element is different
        int i=0;
        while(temp!=0)temp>>=++i;
        i--;

        int left[]=new int[res.length];
        int right[]=new int[res.length];
        int lefti=0;
        int righti=0;
        //split val array into two arrays according to the different pos
        for(int j=0;j<res.length;j++){
            if(((res[j]>>i)&1)==0){
                left[lefti++]=res[j];
            }else{
                right[righti++]=res[j];
            }
        }
        //in left and right array only one element is different,use ^ to find the element
        val[0]=left[0];
        for(int j=1;j<lefti;j++){
            val[0]^=left[j];
        }

        val[1]=right[0];
        for(int j=1;j<righti;j++){
            val[0]^=right[j];
        }

        return val;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章