daily progress
- Find the absolute value:
Math.abs()
topic
Given an array containing all integers from 1 to N, but two numbers are missing. Can you find them in O(N) time and only O(1) space?
Both numbers can be returned in any order.
- Example 1:
- input: [1]
- output: [2,3]
- Example 2:
- Input: [2,3]
- Output: [1,4]
- hint:
- nums.length <= 30000
Source: LeetCode
Link: https://leetcode.cn/problems/missing-two-lcci
The copyright belongs to Leetcode.com. This article is for personal study only, non-commercial use.
answer
The solution starting from the constraints:
I use the bit subscript of the array i
and the sign of the corresponding value nums[i]
to record nums
whether the array contains integers i+1
.
- We can use an N-bit array to record whether N data appear. Since
nums
the array is missing two values, the length is N-2, so we need to create an array of length 2last2
to record whether the last two elements are present.- We use
nums[0: n-3]
andlast2[0: 1]
to record whether N data appear, and if so, modify the value to the opposite number. Since the original values are all greater than 0, when the finaltmp
bit is less than 0, the surface arraynums
contains integerstmp+1
- We use
- Record existence information, traverse
nums
the array:- First, we extract
nums
the raw data that the array contains. The absolute value of the array value is calculated because some of the values will be changed to opposite numbers later:tmp = Math.abs(nums[i])
. - Then, modify
nums[tmp-1]
orlast2[tmp-nums.length-1]
to the original opposite number, so that the original information contained in the array is not lost, and whether the array includes integers is recordedtmp
.
- First, we extract
- Retrieve stored information, iterate over
nums
arrays andlast2
arrays:- If
i
the value at the positionnums[i]
is less than 0, it means thatnums
the array contains integersi+1
- If
i
the value at the positionnums[i]
is greater than 0, it means thatnums
there is a lack of integers in the arrayi+1
, so one of the answers has been found
- If
Advantages: Compared with other problem solutions on the Internet, this method can be more easily extended to the case of missing m data. That is, replace an array of length 2 last2
with an array of length m lastm
.
code:
class Solution {
public int[] missingTwo(int[] nums) {
int[] last2 = {
1, 1};
int[] ans = {
0, 0};
for (int i = 0; i < nums.length; i++){
int tmp = Math.abs(nums[i]);
if (tmp <= nums.length){
nums[tmp-1] = -nums[tmp-1];
}else{
last2[tmp-nums.length-1] = -1;
}
}
for (int i = 0; i < nums.length; i++){
if (nums[i] > 0){
if (ans[0] == 0)
ans[0] = i+1;
else
ans[1] = i+1;
}
}
for (int i = 0; i < last2.length; i++){
if (last2[i] > 0){
if (ans[0] == 0)
ans[0] = i+1+nums.length;
else
ans[1] = i+1+nums.length;
}
}
return ans;
}
}
The execution time and memory consumption are as follows: