class Solution { public int[] singleNumbers(int[] nums) { Arrays.sort(nums); int i = 1,j = 0; int c = 0; ArrayList<Integer> list = new ArrayList<>(); while(i<nums.length){ if(nums[i] != nums[j]){ c++; list.add(nums[j]); j = i; i++; }else{ i+=2; j+=2; if(j == nums.length-1){ c++; list.add(nums[j]); break; } } } int[] res = new int[c]; for(int k = 0;k<c;k++){ res[k] = list.get(k); } return res; } }
位分组
public int[] singleNumbers(int[] nums) { int n = nums.length; int res = nums[0]; int i = 1; while(i<n){ res = (res^nums[i++]); } //将res转换为二进制数 String s = Integer.toBinaryString(res); int j = s.length()-1; while (j>=0){ if(s.charAt(j) == '1'){ break; }else{ j--; } } int j1 = s.length()-1-j; ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<Integer> list2 = new ArrayList<>(); for (int num : nums) { String s1 = Integer.toBinaryString(num); if(s1.length() - 1 - j1<0){ list2.add(num); }else { char c = s1.charAt(s1.length() - 1 - j1); if (c == '1') { list1.add(num); } else { list2.add(num); } } } int[] resList = new int[2]; int res1 = list1.get(0); int k1 = 1; while(k1<list1.size()){ res1 = (res1^list1.get(k1++)); } int res2 = list2.get(0); int k2 = 1; while(k2<list2.size()){ res2 = (res2^list2.get(k2++)); } resList[0] = res1; resList[1] = res2; return resList; }
public int[] singleNumbers(int[] nums) { int n = nums.length; int res = 0; for(int num:nums){ res ^= num; } //获取res中最低位的1 int mask = 1; while ((res & mask) == 0){ mask <<= 1; } int a = 0,b = 0; for(int num:nums){ if((num & mask) == 0){ a ^= num; }else{ b^=num; } } return new int[]{a,b}; }