LeetCode 442. Find All Duplicates in an Array

转载请注明出处:http://www.cnblogs.com/liangyongrui/p/6353922.html 

开个数组 hash的办法 大家都会。

但是这题不能用辅助空间,所以,我给这个方法起名叫别样hash

因为,所有的数字 都在[1,n] 所以可以用数字的正负来表示hash值

具体见代码。

    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < nums.length; ++i) {
            int index = Math.abs(nums[i]) - 1;
            if (nums[index] < 0)
                res.add(index + 1);
            else nums[index] = -nums[index];
        }
        return res;
    }
原文地址:https://www.cnblogs.com/liangyongrui/p/6353922.html