Skip to content
This repository has been archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
49 lines (34 loc) · 1.22 KB

442.md

File metadata and controls

49 lines (34 loc) · 1.22 KB

442. Find All Duplicates in an Array

Description

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]

Thinking Process

  1. Walk through the array, for nums[i] mark the nums[abs(nums[i]) - 1] as its negative counterparts, this indicates that abs(nums[i]) is in the array. If we see the negative number twice, then the number represented by its index must have appeared more than once in the array.

Code

public class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int n = nums.length;
        List<Integer> res = new LinkedList<>();
        
        for(int i = 0; i < n; i++){
            if(nums[Math.abs(nums[i]) - 1] < 0){
                res.add(Math.abs(nums[i]));
            }else{
                nums[Math.abs(nums[i]) - 1] = - Math.abs(nums[Math.abs(nums[i]) - 1]);
            }   
        }
        
        return res;
    }
}

Complexity

  1. O(n) for time
  2. O(1) for space excluding the space needed for output