找出陣列中只出現一次的2個數字,其他數字都出現2次
阿新 • • 發佈:2019-01-11
package lianxi_1; import java.util.ArrayList; import java.util.List; //如果一個數組中只有兩個數字出現1次,其他都是出現2次,請找出這2個數字 //思路:將數字元素全部異或一遍,因為相同的元素異或以後為0,所以結果為出現1次的兩個數字異或結果 //將異或結果按照二進位制中不為0的最低位進行劃分,將陣列分成2個子陣列,那麼出現2次的都是同一個子陣列,出現1次的在不同陣列 //分別對每個子陣列全部異或,即可 public class Exercise_13 { static void fun(int[] a) { int x = 0; for (int i = 0; i < a.length; i++) x ^= a[i]; int j = 1; // 找出異或結果二進位制表示中不為0的最低位 while (true) { if ((x & j) == j) { divArray(a, j); break; } j *= 2; } } private static void divArray(int[] a, int j) { List<Integer> a1 = new ArrayList<>(); List<Integer> a2 = new ArrayList<>(); for (int i = 0; i < a.length; i++) { if ((a[i] & j) == j) a1.add(a[i]); else a2.add(a[i]); } int x = 0; for (int i : a1) { x ^= i; } System.out.println(x); x = 0; for (int i : a2) x ^= i; System.out.println(x); } public static void main(String[] args) { int[] a = new int[] { 1, 1, 5, 6, 7, 4, 8, 4, 3, 8, 7, 3 }; fun(a); } }