1. 程式人生 > >數組中只出現一次的數字

數組中只出現一次的數字

java


題目:一個整型數組裏除了兩個數字之外,其他的數字都出現了兩次。請寫程序找出這兩個只出現一次的數字。

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

//num1,num2分別為長度為1的數組。傳出參數
//將num1[0],num2[0]設置為返回結果
public class Solution {
    public static void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        //System.out.println(map.get(array[1]));
        int k;
        for(int a : array){
        	if(map.get(a) == null){
        		map.put(a, 1); 
        	}else{
        		k = map.get(a);
        		map.put(a, ++k);
        	}
        }

        //遍歷map
        int[] num = new int[2];
        int i = 0;
        Set<Integer> keySet = map.keySet();
		//有了Set集合。就可以獲取其叠代器。
		Iterator<Integer> it = keySet.iterator();
		while(it.hasNext())
		{
			Integer key = it.next();
			//有了鍵可以通過map集合的get方法獲取其對應的值。
			Integer value  = map.get(key);
			if(value == 1){
				num[i] = key;
				//System.out.println("num[" + i + "]" + "=" + num[i]);
				i++;
			}
		}
		num1[0] = num[0];
		num2[0] = num[1];
    }
}


本文出自 “秦斌的博客” 博客,謝絕轉載!

數組中只出現一次的數字