Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
找到数组中只出现一次的数,思路比较简单,就是利用HashMap记录每个数字出现的次数,然后遍历找到出现一次的,可以通过测试
class Solution {
public int singleNumber(int [] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int num : nums) {
if (map.get(num) == null) {
map.put(num, 1);
} else {
map.put(num,map.get(num) + 1);
}
}
for (int num : map.keySet()) {
if (map.get(num) == 1) {
return num;
}
}
return -1;
}
}
下面是一种比较tricky的做法,利用位运算中的异或运算,因为只有一个数字是出现一次的,其余的都是成对出现,因为两个一样的数字经过异或操作后得到0,所以我们异或所有数字之后得到0异或那个只出现一次的,因为0异或任何数字得到的都是本身,所以这样就得到了只出现一次的数字
解法比较tricky,记住就好了
class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
}