Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created April 27, 2022 00:03
Show Gist options
  • Save Turskyi/fc4b6f327e5fb80092bf3ca579c96c9e to your computer and use it in GitHub Desktop.
Save Turskyi/fc4b6f327e5fb80092bf3ca579c96c9e to your computer and use it in GitHub Desktop.
Given an array of integers, nums, each element in the array either appears once or twice. Return a list containing all the numbers that appear twice.
/*
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.
* */
// Input: nums = [1,1,2] Output: [1]
fun findDuplicates(nums: IntArray): List<Int> {
val setToCheck: MutableSet<Int> = mutableSetOf()
val duplicates: MutableList<Int> = mutableListOf()
for (element: Int in nums) {
if (!setToCheck.add(element)) {
duplicates.add(element)
}
}
return duplicates
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment