问题:
package com.example.demo; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Test136 { /** * 借助hash表 */ public int singleNumber(int[] nums) { Set<Integer> set = new HashSet<>(); for (int i = 0; i < nums.length; i++) { if (set.contains(nums[i])) { set.remove(nums[i]); } else { set.add(nums[i]); } } int res = 0; Iterator<Integer> iterator = set.iterator(); while (iterator.hasNext()) { res = iterator.next(); } return res; } /** * 数学方式:res = 2(a + b + c) - (a + a + b + b + c) 结果就是c,也就是要找的值 */ public int singleNumber2(int[] nums) { int sum = 0; Set<Integer> set = new HashSet<>(); for (Integer integer : nums) { sum += integer; set.add(integer); } int twoSum = 0; for (Integer integer : set) { twoSum += integer; } return 2 * twoSum - sum; } /** * 利用位运算,相同的值异或为0,不同的值异或为1 */ public int singleNumber1(int[] nums) { int res = nums[0]; for (int i = 1; i < nums.length; i++) { res ^= nums[i]; } return res; } public static void main(String[] args) { Test136 t = new Test136(); int[] arr = {2, 2, 1, 1, 3}; int i = t.singleNumber2(arr); System.out.println(i); } }
原文:https://www.cnblogs.com/nxzblogs/p/11269770.html