JZ56 數組中只出現一次的兩個數字 題目 一個整型數組裡除了兩個數字只出現一次,其他的數字都出現了兩次。請寫程式找出這兩個只出現一次的數字 思路 演算法實現 既然有兩個數字只出現了一次,我們就統計每個數字的出現次數,利用哈希表的快速根據key值訪問其頻率值。 具體做法: step 1:遍曆數組,用哈 ...
JZ56 數組中只出現一次的兩個數字
題目
一個整型數組裡除了兩個數字只出現一次,其他的數字都出現了兩次。請寫程式找出這兩個只出現一次的數字
思路
演算法實現
既然有兩個數字只出現了一次,我們就統計每個數字的出現次數,利用哈希表的快速根據key值訪問其頻率值。
具體做法:
step 1:遍曆數組,用哈希表統計每個數字出現的頻率。
step 2:然後再遍歷一次數組,對比哈希表,找到出現頻率為1的兩個數字。
step 3:最後整理次序輸出。
代碼
package mid.JZ56數組中只出現一次的兩個數字;
import java.util.*;
public class Solution {
/**
* 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可
*
*
* @param array int整型一維數組
* @return int整型一維數組
*/
public int[] FindNumsAppearOnce (int[] array) {
// write code here
if(array.length == 0) return new int[0];
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for (int value : array) {
if (!map.containsKey(value)) {
map.put(value, 1);
} else {
map.put(value, map.get(value) + 1);
}
}
int index = 0;
for (Integer key: map.keySet()) {
if (map.get(key) == 1) {
result[index] = key;
index++;
}
if (index == 2) break;
}
Arrays.sort(result);
return result;
}
public static void main(String[] args) {
int[] ints = new Solution().FindNumsAppearOnce(new int[]{1, 4, 1, 6});
System.out.println(Arrays.toString(ints));
}
}