image.png

解题思路

位运算

image.png

  1. public int singleNumber(int[] nums) {
  2. int ans = nums[0];
  3. if (nums.length > 1) {
  4. for (int i = 1; i < nums.length; i++) {
  5. ans = ans ^ nums[i];
  6. }
  7. }
  8. return ans;
  9. }

哈希表

  1. public int singleNumber(int[] nums) {
  2. Map<Integer, Integer> map = new HashMap<>();
  3. for (Integer i : nums) {
  4. Integer count = map.get(i);
  5. count = count == null ? 1 : ++count;
  6. map.put(i, count);
  7. }
  8. for (Integer i : map.keySet()) {
  9. Integer count = map.get(i);
  10. if (count == 1) {
  11. return i;
  12. }
  13. }
  14. return -1; // can't find it.
  15. }