Single Number I
题解
https://leetcode.com/problems/single-number/
Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
相同的数异或为0。
0和任何数异或都为这个数。
所以 全部的数异或就为那一个数。
Code
public class Solution {
public int singleNumber(int[] nums) {
int res = 0;
for (int i = 0; i < nums.length; i++) {
res = res ^ nums[i];
}
return res;
}
}
Single Number II
题解
https://leetcode.com/problems/single-number-ii/
Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
求得遍历每一个数,求得某一位上,1的个数,如果存在3的余数,则那个数就是多出来的Single one 速度很慢。
Code
public class Solution {
public int singleNumber(int[] nums) {
int length = nums.length;
int res = 0;
for (int i = 0; i < 32; i++) {
int mask = 1 << i;
int count = 0;
for (int j = 0; j < length; j++) {
if ((nums[j] & mask) == mask) {
count++;
}
}
if (count % 3 != 0) {
res += mask;
}
}
return res;
}
}
Single Number III
题解
https://leetcode.com/problems/single-number-iii/
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
此题的解法,对于三个题目都适用,只是方法实在是太笨了,无奈,网上的妙趣的解法我没有通透。目前就先写这个方法吧,等哪天我弄明白了,再贴出代码。
Code
public class Solution{
public int[] singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])) {
map.put(nums[i], 1);
} else {
map.put(nums[i], map.get(nums[i]) + 1);
}
}
int[] res = new int[2];
int i = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() == 1) {
res[i] = entry.getKey();
i++;
}
}
return res;
}
}