Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

448. Find All Numbers Disappeared in an Array #159

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

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]; } }

    for(int j =1 ;j <= nums.length ; j++){
        if(nums[j-1] > 0){
            result.add(j);
        }
    }
    return result;

}
Shawngbk commented 7 years ago

google