题解 | 数组中只出现一次的两个数字
数组中只出现一次的两个数字
https://www.nowcoder.com/practice/389fc1c3d3be4479a154f63f495abff8
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型一维数组
*/
public int[] FindNumsAppearOnce (int[] nums) {
// write code here
HashSet<Integer> map = new HashSet<>();
int len = nums.length;
int[] ans = new int[2];
for(int num:nums){
if(map.contains(num)){
map.remove(num);
}
else{
map.add(num);
}
}
int i=0;
if(i<2){
for(int m:map){
ans[i]=m;
i++;
}
}
Arrays.sort(ans);
return ans;
}
}
联想到的是HashSet里面可以保留唯一元素,那么如果contains说明在之前存在 就移除,这样就只剩下一次的

嘉士伯公司氛围 714人发布