數組中出現一個數字出現次數的問題

一個數組中只有一個數字出現奇數次,其他都是出現偶數次,時間復雜度為O(n);

/**
 * Author: Taoyongpan
 * Date: Created in 9:35 2018/6/14
 * 一個數組中只有一個數只出現了奇數次,其他都是出現偶數次,時間復雜度為O(n)
 */
public class Test10 {
    public static void main(String[] args) {
        int[] arr = {1,1,2,3,4,2,3,};
        int res = arr[0];
        for (int i = 1 ; i< arr.length;i++){
            res^=arr[i];
        }
        System.out.println(res);
    }
}

一個數字有兩個數出現奇數次其他都是出現偶數次

/**
 * Author: Taoyongpan
 * Date: Created in 9:42 2018/6/14
 * 數組中只出現一次的兩個數字
 * 方法,將 兩個不同的數分別放置到兩個數組中,
 * 通過二進制的某一位,是0或者1將整個數組拆分開
 */
public class Test12 {
    public static void main(String[] args) {
        int[] arr = {1,1,2,3,4,2,};
        int res = 0;
        int j = 0;
        int num1 = 0;
        int num2 = 0;
        for (int i = 0 ; i < arr.length ; i++ ){
            res^=arr[i];
        }
        for (j = 0 ;j < 32;j++){
            if (((res>>j)&0)==0){
                break;
            }
        }
        for (int i = 0;i<arr.length;i++){
            if (((arr[i]>>j)&1)==1)
                num1^=arr[i];
            else
                num2^=arr[i];
        }
        System.out.println(num1);
        System.out.println(num2);
    }
}

一個數組中只有一個數出現一次,其他都是出現三次,輸出這個數:

/**
* Author: Taoyongpan
* Date: Created in 9:38 2018/6/14
* 一個數組中只有一個數字出現了一次 ,其他都是出現了三次,
* 在O(n)的時間復雜度中,求出這個只出現一次的數
* 解法:當一個數組每一個數都出現三次的時候,二進制表示上面每一位 1的個數肯定是三的倍數,
* 當不是三的倍數的時候,說明只出現一次的那個數此位上為1
*/
public class Test11 {
  public static void main(String[] args) {
      int[] a = {1,1,1,2,2,2,3};
      int[] bits = new int[32];
      for (int i = 0; i < a.length; i++)
          for (int j = 0; j < 32; j++)
              bits[j] += ((a[i] >> j) & 1);
      int res = 0;
      for (int j = 0; j < 32; j++)
          if (bits[j] % 3 != 0)
              res += (1 << j);
      System.out.println(res);
  }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容