1. 程式人生 > >不用比較找到數組中兩個不同的值

不用比較找到數組中兩個不同的值

java 算法

/** * 找到數組中兩個不同的值 * / public static void main(String[] args) { int[] arr={2,2,1,1,3,4}; int eo = eh(arr); int offset = getOffset(eo); int eo1 = 0; for(int i:arr){ if(((i>>offset)&1)==1)continue; eo1 ^= i; } System.out.println((eo^eo1) +" "+eo1); } public static int eh(int[] n){ int eo = 0; for(int i:n){ eo ^= i; } return eo; } public static int getOffset(int n){ int i = 0; while((n&1)!=1){ n = n>>1; i++; } return i; }


不用比較找到數組中兩個不同的值