Givemepass's Android 惡補筆記

如何找出陣列內單一元素

| Comments

今天有朋友問了這個問題, 試著寫看看,

public int findSingleNum(int[] list){
    HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
    for(Integer i : list){
        if(map.containsKey(i)){
            map.get(i).add(i);
        } else{
            ArrayList<Integer> array = new ArrayList<Integer>();
            array.add(i);
            map.put(i, array);
        }
    }
    for(Integer key : map.keySet()){
        ArrayList<Integer> array = map.get(key);
        if(array.size() % 2 != 0){
            return Integer.valueOf(key);
        }
    }
    return -1;
}

結果他的答案是這樣

int[] a = {1,1,2,3,4,9,5,4,1,5,3,2,1};

int result = a[0];
for(int i = 1; i < a.length; i++){
    result ^= a[i];
}
System.out.print(result);

輸惹

Comments

comments powered by Disqus