LeetCode --- 只出現一次的數字 III
阿新 • • 發佈:2018-12-26
給定一個整數陣列 nums,其中恰好有兩個元素只出現一次,其餘所有元素均出現兩次。 找出只出現一次的那兩個元素。
示例 :
輸入: [1,2,1,3,2,5]
輸出: [3,5]
注意:
結果輸出的順序並不重要,對於上面的例子, [5, 3] 也是正確答案。
你的演算法應該具有線性時間複雜度。你能否僅使用常數空間複雜度來實現?
class Solution {
public int[] singleNumber(int[] nums) {
Map<Integer, Long> map = Arrays.stream(nums).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int [] res = new int[2];
if (!map.isEmpty()) {
for (Map.Entry entry: map.entrySet()) {
if (entry.getValue().equals(1L)) {
if (res[0] == 0) {
res[0] = (int) entry.getKey();
} else {
res[1 ] = (int) entry.getKey();
}
}
}
}
return res;
}
}