2012-08-09 65 views
5

對於初學者,我也看看這些問題:發現許多不爲O重複(n)的時間O(1)空間

Given an array of integers where some numbers repeat 1 time, some numbers repeat 2 times and only one number repeats 3 times, how do you find the number that repeat 3 times

Algorithm to find two repeated numbers in an array, without sorting

這一個不同:

給定整數的未排序的陣列與一個唯一的數字,其餘的號碼重複3次,即 :

{4,5,3, 5,3,4, 1, 4,3,5 } 

我們需要找到在O(n)的時間和O(1)空間這個獨特的數字

注意:這不是一門功課,只是我我碰到

+0

相關:[在其中的每個單元被重複奇數次的陣列查找一個元件和僅一個出現一次](HTTP://計算器。 COM/q/7338070/4279) – jfs 2012-08-09 14:11:00

回答

7

怎麼來到這個一個有趣的問題之一:

理念:做按位加法模3

#include <stdio.h> 

int main() { 
    int a[] = { 1, 9, 9, 556, 556, 9, 556, 87878, 87878, 87878 }; 
    int n = sizeof(a)/sizeof(int); 
    int low = 0, up = 0; 

    for(int i = 0; i < n; i++) { 
     int x = ~(up & a[i]); 
     up &= x; 
     x &= a[i]; 
     up |= (x & low); 
     low ^= x; 
    } 
    printf("single no: %d\n", low); 
} 
+1

我剛剛編譯了你的算法,它似乎工作 ,你只使用按位操作。 小心解釋它是如何工作的? – candyman 2012-08-09 13:14:28

+0

@candyman:以列表中每個數字的二進制表示。計算每位發生多少次(模3)。對於每個等於1的計數器,在結果值中設置相應的位。例如:{4,5,3,5,3,4,1,4,3,5}→bit0 = 7 = 1,bit1 = 3 = 0,bit2 = 6 = 0→result = 1 – 2012-08-09 13:18:58

+0

aah got它,謝謝Evgeny,你的解決方案也是正確的 – candyman 2012-08-09 13:22:08

相關問題