1. 程式人生 > >【演算法】給定一個數組,除了一個數出現1次之外,其餘數都出現3次,輸出出現一次的那個數。

【演算法】給定一個數組,除了一個數出現1次之外,其餘數都出現3次,輸出出現一次的那個數。

給定一個數組,除了一個數出現1次之外,其餘數都出現3次。找出出現一次的數。如:{1, 2, 1, 2, 1, 2, 7},找出7.格式:第一行輸入一個數n,代表陣列的長度,接下來一行輸入陣列A[n],(輸入的陣列必須滿足問題描述的要求),最後輸出只出現一次的數。

package yn;

import java.util.Scanner;

public class OutputMin {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int
i = 0; int j = 0; int k = 0; int n = input.nextInt(); int a[] = new int[n]; Scanner in = new Scanner(System.in); System.out.println("請輸入一個數組"); for (i = 0; i < n; i++) { a[i] = in.nextInt(); System.out.print(a[i] + " "
); } System.out.println(); for (j = 0; j < n; j++) { int f = 0; for (k = 0; k < n; k++) { if (a[j] == a[k]) { f++; } } if (f == 1) { System.out.println(a[j]); break
; } } } }

上面這種方法絕大多數人肯定都會,但是我覺得演算法效率肯定很低。來想想另外一種方法。

首先看看題目要求:

陣列A中,除了某一個數字x之外,其他數字都出現了三次,而x出現了一次。請給出最快的方法找到x。應該如何思考呢?

如果是兩個相同的就可以利用兩個相同的數異或結果為0來計算的,但這個題目中其他數字是出現了3次,因此肯定不可以再使用異或了。

我們換一個角度來看,如果陣列中沒有x,那麼陣列中所有的數字都出現了3次,在二進位制上,每位上1的個數肯定也能被3整除。如{1, 5, 1, 5, 1, 5}從二進位制上看有:

1:0001

5:0101

1:0001

5:0101

1:0001

5:0101

二進位制第0位上有6個1,第2位上有3個1.第1位和第3位上都是0個1,每一位上的統計結果都可以被3整除。而再對該陣列新增任何一個數,如果這個數在二進位制的某位上為1都將導致該位上1的個數不能被3整除。因此通過統計二進位制上每位1的個數就可以推斷出x在該位置上是0還是1了,這樣就能計算出x了。

推廣一下,所有其他數字出現N(N>=2)次,而一個數字出現1次都可以用這種解法來推匯出這個出現1次的數字。

例子程式:

package yn;

import java.util.Arrays;

public class OutputMinJava {
    public static void main(String[] args) {
        int a[] = { 2, 3, 1, 2, 3, 4, 1, 2, 3, 1, 4, 4, 5 };
        for (int j = 0; j < a.length; j++) {
            System.out.print(a[j]);
        }
        System.out.println();
        System.out.println(findNumber(a, a.length));
    }

    public static int findNumber(int a[], int n) {
        int bits[] = new int[32];
        Arrays.fill(bits, 0);
        int i, j;
        for (i = 0; i < n; i++)
            for (j = 0; j < 32; j++)
                bits[j] += ((a[i] >> j) & 1);
        // 如果某位上的結果不能被整除,則肯定目標數字在這一位上為
        int result = 0;
        for (j = 0; j < 32; j++)
            if (bits[j] % 3 != 0)
                result += (1 << j);
        return result;
    }
}

這裡寫圖片描述