Post

Leetcode - 442. Find All Duplicates in an Array

Leetcode - 442. Find All Duplicates in an Array

Hits

  • Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

    You must write an algorithm that runs in O(n) time and uses only constant extra space.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func findDuplicates(nums []int) []int {
    i := 0

    for i<len(nums){
        indexWhereItShouldBe := nums[i]-1
        if nums[i]!=nums[indexWhereItShouldBe]{
            nums[i], nums[indexWhereItShouldBe] = nums[indexWhereItShouldBe], nums[i]
        }else{
            i++
        }
    }

    duplicateNumbers := make([]int, 0)
	for i = 0; i < len(nums); i++ {
		if nums[i] != i+1 { 
			duplicateNumbers = append(duplicateNumbers, nums[i]) 
		}
	}
	return duplicateNumbers
    
}
This post is licensed under CC BY 4.0 by the author.