https://leetcode-cn.com/problems/single-number/solution/xue-suan-fa-jie-guo-xiang-dui-yu-guo-cheng-bu-na-y/
方法一:哈希表
class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (Integer i : nums) {
Integer count = map.get(i);
count = count == null ? 1: ++count;
map.put(i, count);
}
for (Integer i: map.keySet()) {
Integer count = map.get(i);
if (count == 1) {
return i;
}
}
return -1;
}
}
方法二:亦或
class Solution {
public int singleNumber(int[] nums) {
int ans = nums[0];
if (nums.length > 1) {
for (int i = 1; i < nums.length; i++) {
ans ^= nums[i];
}
}
return ans;
}
}
本文介绍了LeetCode上单数问题的两种解决方案:使用哈希表和亦或操作。哈希表方法通过计数查找只出现一次的数字,而亦或方法利用位运算的性质,快速找到目标数字。
1051

被折叠的 条评论
为什么被折叠?



