给定一个整数数组 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;
}
}