Single Number
思路一: 用 set 过滤,剩下唯一一个就是目标数字
public int singleNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (set.contains(num)) {
set.remove(num);
} else {
set.add(num);
}
}
return set.iterator().next();
}
思路二: 用位操作符 XOR,出现两次的数字会相互抵消,刚好剩下就是目标数字
public int singleNumber(int[] nums) {
int n = 0;
for (int i = 0; i < nums.length; i++) {
n ^= nums[i];
}
return n;
}
标签:set,nums,int,singleNumber,num,136,easy,leetcode
From: https://www.cnblogs.com/iyiluo/p/16804868.html