Single Number I+II+III

Expected:linear runtime complexity, constant space complexity.(像當初的我直接用關聯容器暴力解決…)

Single Number I

Given an array of integers, every element appears twice except for one. Find that single one.

public class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for(int i=0;i<nums.length;i++)
            result = result ^ nums[i];
        return result;
    }
}
//只有這道完全是自己想到的...因爲想到一種用位操作實現兩數互換的方法(不需要用temp):
// A = A^B;
// B = A^B;
// A = A^B;

Single Number II

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

//方法一(Single Number I也可以用)
//統計數組中的數字每一位上'1'的個數,對3取餘即可得到SingleNumber在該位是'0'還是'1'
public class Solution {
    public int singleNumber(int[] nums) {
        int temp;
        int result = 0;
        for(int i=0;i<32;i++){
            temp = 0;
            for(int j=0;j<nums.length;j++){
                temp += (nums[j]>>i)&1;
            }
            temp %= 3;
            result |= (temp<<i);
        }

        return result;
    }
}

//方法二:amazing...
public class Solution {
    public int singleNumber(int[] nums) {
        int one=0;
        int two=0;
        int i,j,k;
        //其中的one代表目前爲止number出現了一次
        //two代表出現了兩次
        //three代表出現了三次
        for(i=0; i<nums.length; i++)
        {
            two = two |(one&nums[i]);//當one爲'1'時,two爲'1'(已經出現過一次,現在又出現一次),當one爲‘0’時,two不變
            one = one^nums[i];//出現了奇數次則爲非0

            int three = two&one;
            two = two^three; //當one和two都達到非零時,用three將two置零
            one = one^three; //用three將one置零
        }

        return one|two;
    }
}

Single Number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

public class Solution {
    public int[] singleNumber(int[] nums) {
        int attempt = 0;
        for(int i=0;i<nums.length;i++){
            attempt ^= nums[i];//得到兩個結果的異或
        }
        //如何把二者分離?
        //找到異或結果中某位爲'1'的位置,然後將原數組中此位爲'1'的分爲一類,爲'0'的分爲一類
        //爲了計算考慮,通常尋找最後一個'1'的位置,而且有一個很巧妙的公式:
        int lastOne = attempt & (~(attempt-1));
        int a = 0;
        int b = 0;
        for(int i=0;i<nums.length;i++){
            if( (nums[i]&lastOne) == 0) a^=nums[i];
            else b^=nums[i];
        }

        int[] result = new int[2];
        result[0] = a;
        result[1] = b;

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