BiruLyu
7/3/2017 - 4:39 AM

442. Find All Duplicates in an Array(1st).java

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<Integer>();
        if (nums == null || nums.length < 1) return res;
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            int idx = Math.abs(nums[i]) - 1;
            if (nums[idx] < 0) {
                res.add(idx + 1);
            } else {
                nums[idx] *= -1;
            }
            //nums[idx] *= -1;
        }
        return res;
    }
}
public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int[] HashTable = new int[nums.length+1];
        List<Integer> ret = new ArrayList<Integer>();
        for(int i=0 ; i<nums.length; i++){
            if(HashTable[nums[i]]==0) HashTable[nums[i]]++;
            else ret.add(nums[i]);
        }
        return ret;
    }
}