Leetcode442 Find All Duplicates in an Array

这个题还是很有意思的,因为它限制了时间复杂度在O(n),空间复杂度小于O(c)。

对于这种要求优化程度很高的题,首先不能被约束条件限制住思路。如果没有约束条件,这题该怎么做呢?十分简单,另设一数组或bucket数组,记录元素出现次数,出现次数等于2的就是结果。(提交结果中最高的6ms答案就是使用了bucket数组。但是其实这是违规的,不过leetcode并没有检查空间复杂度,于是它通过了。)

但是,题目要求我们不能使用额外空间,那该咋做?不能使用额外空间一般是指:不能开辟一个新的长度与n相关的数组或者Collections。但是可以使用一个或多个变量。另外题目要求返回一个List<Integer>,这个肯定是要建立的。

然后我们看题目要求Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

由此可以受到启发,使用bucket数组寸出现次数,但是不可以使用。再想,既然记录次数的bucket数组和原数组一样长,那我们可以使用原数组nums记录次数呀,于是思路就形成了,方法1:

public class FindAllDuplicatesInAnArray442 {
    public List<Integer> findDuplicates(int[] nums) {
        for(int i=0;i<nums.length;i++) {
            int p = nums[i];
            if(p>0) nums[i]=0;
            while(p>0) {
                if(nums[p-1]>0) {
                    int temp = nums[p-1];
                    nums[p-1] =-1;
                    p=temp;
                }
                else {
                    nums[p-1]--;
                    p=0;
                }
            }
        }
        List<Integer> result = new ArrayList<>();
        for(int i=0;i<nums.length;i++) {
            if(nums[i]==-2) result.add(i+1);
        }
        return result;
    }
}

去掉使用额外的bucket数组的方法,也算是beat100%了。

posted @ 2019-03-22 00:22  大胖子球花  阅读(70)  评论(0)    收藏  举报