442. Find All Duplicates in an Array

题目

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Input:[4,3,2,7,8,2,3,1]
Output:[2,3]

分析

给定一个数组大小为n,数组中的数都在[1,n]范围内,有的数出现一次,有的出现两次,找出所有出现两次的数。
这道题要求O(n)时间复杂度和不用额外空间,其实是要利用数有范围这个条件,[1,n]范围正好可以对应数组的下标,如果出现了一次就对相应下标的数据做一些不影响下次读取的变化,比如乘以-1,表示这个下标已经出现过一次,下次再找到这个下标时发现这个数已经是负数了,就表示是出现了两次了。这种方法也可以得出出现多次的结果。

代码

// when find a number i, flip the number at position i-1 to negative. 
// if the number at position i-1 is already negative, i is the number that occurs twice.

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);
        nums[index] = -nums[index];
    }
    return res;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容