LeetCode-442.Find All Duplicates in an Array

时间:2022-03-13 04:38:03

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?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

Solutions:

class Solution {
    //Input:[4,3,2,7,8,2,3,1]
    //index:[3,2,1,6,7,1,2,0] -> index对应nums中的值变为负数
    //index的值判断是否为负即可知道是否重复
    //时间复杂度O(n)
    
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> list = new ArrayList<>();
        
        for(int i=0;i<nums.length;i++){
            int index = Math.abs(nums[i])-1;
            if(nums[index]<0)
                list.add(index+1);
            nums[index] = -nums[index];
        }
        return list;
    }
}