Sol1:存到hashset,便利两次
public class Solution {
public List findDisappearedNumbers(int[] nums) {
HashSet set = new HashSet();
for(int i : nums) {
set.add(i);
}
List res = new ArrayList<>();
for(int i = 1; i <= nums.length; i++) {
if(set.contains(i))
continue;
else
res.add(i);
}
return res;
}
}
sol2:in place
Think we surely have to negate anytime we are given an array with values from 1 to the length of array. If anyone has a better idea, will be happy to hear.
The steps followed in this is:
Negate each number while traversing
Run again and find the index that is not negated.
List result = new ArrayList();
for( int i=0;i< nums.length; i++){
int index = nums[i];
if(nums[Math.abs(index)-1] > 0){
nums[Math.abs(index)-1]= -nums[Math.abs(index)-1];
}
}
Sol1:存到hashset,便利两次 public class Solution { public List findDisappearedNumbers(int[] nums) {
HashSet set = new HashSet();
for(int i : nums) {
set.add(i);
}
List res = new ArrayList<>();
for(int i = 1; i <= nums.length; i++) {
if(set.contains(i))
continue;
else
res.add(i);
}
return res;
}
}
sol2:in place Think we surely have to negate anytime we are given an array with values from 1 to the length of array. If anyone has a better idea, will be happy to hear.
The steps followed in this is:
Negate each number while traversing Run again and find the index that is not negated. List result = new ArrayList();
for( int i=0;i< nums.length; i++){
int index = nums[i];
if(nums[Math.abs(index)-1] > 0){
nums[Math.abs(index)-1]= -nums[Math.abs(index)-1];
}
}