Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
Input: [4,3,2,7,8,2,3,1] Output: [5,6]
The index 0,...,N-1 maps to the array 1,...,N. Use the negtive sign at index m-1 to indicate number m exist in the array.
a. loop i from 0...N, the number exists is m=abs(nums[i]), (use abs() because nums[i] may already be set to negative). Set nums at index (m-1) to -nums[m-1].
b. loop again, if(nums[i]>0), i+1 is not in the array.
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
int N = nums.size();
for(int i=0, n; i<N; i++) {
n = abs(nums[i]) - 1;
if(nums[n]>0)
nums[n] = -nums[n];
}
for(int i=0; i<N; i++) {
if(nums[i]>0)
res.push_back(i+1);
}
return res;
}
Solution 2:
Similar to 1, but adding N to nums[i] if value i+1 exists. Those indices i for nums[i]<N indicate i+1 is missing.
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
int N = nums.size();
for(int i=0; i<N; i++) {
nums[(nums[i]-1)%N] += N;
}
for(int i=0; i<N; i++) {
if(nums[i]<=N)
res.push_back(i+1);
}
return res;
}
Solution 3:
Loop and swap the values so that the index i matches nums[i]%N, the index doesn't match its value is the value missing. For example, [4,3,2,7,8,2,3,1] will be [8,1,2,3,4,2,3,7], the indice [5,6] do not match their values, so [5,6] is the result.
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int> res;
int N = nums.size();
for(int i=0; i<N; i++) {
while(nums[i] != nums[nums[i]%N]) {
swap(nums[i],nums[nums[i]%N]);
}
}
for(int i=0; i<N; i++) {
if(nums[i]%N!=i)
res.push_back(i==0? N:i);
}
return res;
}
No comments:
Post a Comment