Problem_Single Number I, II, III - xwu36/LeetCode GitHub Wiki
136. Single Number
Problem:
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Algorithm:
XOR
137. Single Number II
Problem:
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Algorithm:
For each bit, we know it could only be 3 * k + m and m is the bit of the single number,
so we simply do mod operation by 3, we'll get m as the right bit.
Code:
class Solution {
public int singleNumber(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int n = nums.length;
int res = 0;
for(int i = 0; i < 32; i++){
int sum = 0;
for(int num : nums){
sum += (num >> i) & 1;
}
sum = sum % 3;
res |= sum << i;
}
return res;
}
}
260. Single Number III
Problem:
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].
Note:
The order of the result is not important. So in the above example, [5, 3] is also correct.
Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
Algorithm:
We do xor for all the numbers and we'll get the xor result (diff) of two single elements.
The basic idea here is that we need to separate all the given elements into two groups.
What we need to do is to find a mask which & some numbers is alway zero, and & the others is not zero.
This mask can be obtained by diff & (-diff), which is the last different of these two single elements
Code:
class Solution {
public int[] singleNumber(int[] nums) {
int diff = 0;
for (int num : nums)
diff ^= num;
diff &= -diff;
int[] rets = {0, 0};
for (int num : nums){
if ((num & diff) == 0) // the bit is not set
rets[0] ^= num;
else // the bit is set
rets[1] ^= num;
}
return rets;
}
}