方法一 哈希
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型一维数组 */ public int[] FindNumsAppearOnce (int[] nums) { // write code here Map<Integer,Integer> map=new HashMap<>(); for(int num:nums){ map.put(num,map.getOrDefault(num,0)+1); } int [] res=new int[2]; int index=0; for(int num:map.keySet()){ if(map.get(num)==1){ res[index++]=num; } } Arrays.sort(res); return res; } }
方法二 异或
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型一维数组 */ public int[] FindNumsAppearOnce (int[] nums) { // write code here int res1=0; int res2=0; int temp=0; for(int num:nums){ temp^=num; } int k=1; while((k&temp)==0){ k<<=1; } for(int num:nums){ if((num&k)==0){ res1^=num; }else{ res2^=num; } } if(res1<res2){ return new int[]{res1,res2}; }else{ return new int[]{res2,res1}; } } }