java數據結構: 統計5億數字去重後的個數(byte數組標記數字)

面試題:

內存爲300M, 設計一個算法, 計算5億 int類型數去重後, 還有多少個數?

/**
 * //傳入5億個:  int 型數據: 計算去重後的 , 數字個數 ===》
 *  限制要求 :  內存僅 300M
 *
 *  int a:  4byte
 *  300M   -->300*1024*1024byte:  7800萬 個int , 存放不了3億個Int !
 *  
 *  思路: 把byte拆分爲8bite使用,  形成==>7800萬 * 8 byte:  6億個位置可供使用
 *          1,定義數組容量: Integer.Max /8 +1
 *          2, 判斷每個數字在數組的位置(類似x, y軸座標):  (x= num/8,  y=num%8 )
 *
 */
public class BillionNumsCount {

    @Test
    public void getCount(){

        int [] arr={2,34,4,Integer.MAX_VALUE,    2,Integer.MAX_VALUE};
        int[] containor= new int[Integer.MAX_VALUE / 8 +1 ];
        long count =0;


        for (int num : arr) {
            int x=num / 8;
            int y=num % 8;

            //在數組中定位---標記該數
            byte val1=  (byte) (1<< y);
            int item=containor[x];

            if( (item & val1) ==0){

                containor[x]=  (item | val1);//在該元素的 byte[y] 位置: 標記1
                count ++;
            }

        }//for
        System.out.println(count);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章