Solution URL
https://leetcode.com/submissions/detail/413588394/
代码
class Solution {
public int singleNumber(int[] nums) {
// //HashMap法
// Map<Integer, Integer> map = new HashMap<>();
// //遍历nums,将num和出现的频率以k-v保存
// for(int num: nums){
// map.put(num, map.getOrDefault(num, 0) + 1);
// }
// //遍历map,找到v为1的k
// int res = 0;
// for(Integer key: map.keySet()){
// if(map.get(key) == 1) res = key;
// }
// return res;
//异或法
//ans: https://leetcode-cn.com/problems/single-number/solution/xue-suan-fa-jie-guo-xiang-dui-yu-guo-cheng-bu-na-y/
int ans = nums[0];
if(nums.length > 1){
for(int i = 1; i < nums.length; i++){
ans ^= nums[i];
}
}
return ans;
}
}