关于在n-1的数组中找到那个被减去的数及异或与位与
生活随笔
收集整理的這篇文章主要介紹了
关于在n-1的数组中找到那个被减去的数及异或与位与
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 有1到N共 n-1個數,問少了哪個數
// 有序數組(如果是無序數組那么將a[i] 移動至 a[a[i]] 這樣子就成功排序了)
//其實可以采用byte數組的來做,感覺會更快
//當然,這個更多的是用在1-n 共n+1個數,問多出來的那個數是多少?這個時候可以不確認一下N是多少,然后,連續的每4個數異或出來的結果為0,這樣即省去了數組的開銷
public static void lessOne(int[] a) {int fruit = 0;int count = 0;for (int i = 0; i < a.length; i++) {count++;fruit ^= a[i];if (count == 4) {if (fruit == 0) {count = 0;} else {System.out.println("Less is:" + i);break;}}} }?
下面為測試代碼
int[] a = new int[100]; for (int i = 0; i < a.length; i++) {if (i == 67)continue;a[i] = i; } //也可以使用已提供的方法進行排序,但不建議 //Arrays.sort(a); lessOne(a);?
?
// 有一組數,中間有兩個數的出現次數為奇數次,問是哪兩個數
public static void lesstwoj() { int[] a = { 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8 };int sum = 0;for (int i : a) {sum ^= i;}int count = 0;int temp = sum;while ((temp & 1) == 0) {temp >>= 1;count++;}int one = 0;for (int i : a) {if (((i >> count) & 1) != 0) {one ^= i;}}int sec = sum ^ one;System.out.println("one:" + one);//第一個數System.out.println("sec:" + sec);//第二個數 }?
?
// 采用異或運算來進行交換位置
//不借助于第三個數
public static void swap(int a, int b) {if (a != b) {a = a ^ b;b = a ^ b;a = a ^ b;}System.out.println("one-- a:" + a + " b:" + b); }?
轉載于:https://www.cnblogs.com/ahhy/p/4383668.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的关于在n-1的数组中找到那个被减去的数及异或与位与的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 竟也可以写网页前端了
- 下一篇: HDU 题目分类