數(shù)組中出現(xiàn)一個(gè)數(shù)字出現(xiàn)次數(shù)的問(wèn)題

一個(gè)數(shù)組中只有一個(gè)數(shù)字出現(xiàn)奇數(shù)次,其他都是出現(xiàn)偶數(shù)次,時(shí)間復(fù)雜度為O(n);

/**
 * Author: Taoyongpan
 * Date: Created in 9:35 2018/6/14
 * 一個(gè)數(shù)組中只有一個(gè)數(shù)只出現(xiàn)了奇數(shù)次,其他都是出現(xiàn)偶數(shù)次,時(shí)間復(fù)雜度為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);
    }
}

一個(gè)數(shù)字有兩個(gè)數(shù)出現(xiàn)奇數(shù)次其他都是出現(xiàn)偶數(shù)次

/**
 * Author: Taoyongpan
 * Date: Created in 9:42 2018/6/14
 * 數(shù)組中只出現(xiàn)一次的兩個(gè)數(shù)字
 * 方法,將 兩個(gè)不同的數(shù)分別放置到兩個(gè)數(shù)組中,
 * 通過(guò)二進(jìn)制的某一位,是0或者1將整個(gè)數(shù)組拆分開(kāi)
 */
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);
    }
}

一個(gè)數(shù)組中只有一個(gè)數(shù)出現(xiàn)一次,其他都是出現(xiàn)三次,輸出這個(gè)數(shù):

/**
* Author: Taoyongpan
* Date: Created in 9:38 2018/6/14
* 一個(gè)數(shù)組中只有一個(gè)數(shù)字出現(xiàn)了一次 ,其他都是出現(xiàn)了三次,
* 在O(n)的時(shí)間復(fù)雜度中,求出這個(gè)只出現(xiàn)一次的數(shù)
* 解法:當(dāng)一個(gè)數(shù)組每一個(gè)數(shù)都出現(xiàn)三次的時(shí)候,二進(jìn)制表示上面每一位 1的個(gè)數(shù)肯定是三的倍數(shù),
* 當(dāng)不是三的倍數(shù)的時(shí)候,說(shuō)明只出現(xiàn)一次的那個(gè)數(shù)此位上為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);
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容