CSDN Topic Challenge Phase 2
Participation Topic: Algorithm Solution
Article directory
Topic link and description
https://leetcode.cn/problems/missing-two-lcci/
Keywords: sum in-place hash XOR
The first reaction is to solve violently again. After sorting, take two, but the time is not enough
Method 1: Summation
- The sum of all 1-n can be obtained by using the arithmetic difference formula
- Traversing nums can get the sum after missing 2 digits
- The subtraction of two numbers is the sum of the two numbers we are looking for
- sum/2, you can get the middle value of two numbers, one on the left and one on the right
- In the same way, we can get the sum of 1-sum/2 according to the arithmetic difference formula
- You can also find the sum in the 1-sum/2 array
- Subtract the two numbers to get the number on the left, sum- the number on the left is the number on the right
run screenshot
the code
public int[] missingTwo(int[] nums) {
int n = nums.length + 2;
long sum = 0;
for (int x: nums) sum += x;
long sumTwo = n * (n + 1) / 2 - sum;
long limits = sumTwo / 2;
sum = 0;
for (int x: nums)
if (x <= limits) sum += x; // 两个数不相同那么一个大于,一个小于
long one = limits * (limits + 1) / 2 - sum;
return new int[]{
(int)one, (int)(sumTwo - one)};
}
Method 2: XOR
The principle is similar to summation, XOR (the same is 0, different is 1) is used:
- a xor a = 0
- XOR follows arithmetic combination (1-n XOR 1-n XOR with missing two bits = XOR with two missing bits):
- a xor b xor b = a
- a xor b = c and a xor b xor a=c xor a, i.e. b = c xor a
- Then finally get two missing XORs. Through the lowbit, one must be 1 and the other is 0 (otherwise the two numbers are equal), and then the previous two XORs of all members are repeated. Through the boundary, one of them can be obtained. Then XOR with the previous result to get another
run screenshot
the code
public int[] missingTwo(int[] nums) {
int n = nums.length + 2;
int xor = 0;
for (int v : nums) {
xor ^= v;
}
for (int i = 1; i <= n; ++i) {
xor ^= i;
}
int diff = xor & (-xor);
int a = 0;
for (int v : nums) {
if ((v & diff) != 0) {
a ^= v;
}
}
for (int i = 1; i <= n; ++i) {
if ((i & diff) != 0) {
a ^= i;
}
}
return new int[] {
a, xor ^ a};
}
Method 3: In-place hash
Through the array subscript and value mapping, no one is exchanged, and finally the missing number is obtained after traversing once. This is consistent with the solution to the previous problem.
run screenshot
the code
public int[] missingTwo(int[] nums) {
int[] hash = new int[nums.length+2];
for(int i = 0 ; i < nums.length;i++){
hash[nums[i]-1]++;
}
//hash记录
int[] re = new int[2];
int i = 0;
for(int j = 0 ; j < hash.length;j++){
//把0排除在外
if(hash[j] == 0){
re[i++] = j+1;
}
}
return re;
}
end
It's a bit easy to find one hundred of this question
Welcome to communicate in the comment area, check in every day, and rush! ! !