Senior
/* Given an array of numbers nums of length n, each number can be either unique or appear twice. Numbers are in the range [1, n]. Write a function that returns an array of numbers that appear twice. Examples: Input: nums = [4, 3, 2, 7, 8, 2, 3, 1] Output: [2, 3] Input: nums = [2, 2, 1] Output: [2] */
sobes.tech AI
Answer from AI
go func findDuplicates(nums []int) []int { duplicates := []int{} for _, num := range nums { index := abs(num) - 1 if nums[index] < 0 { duplicates = append(duplicates, abs(num)) } else { nums[index] = -nums[index] } } return duplicates }
func abs(a int) int { if a < 0 { return -a } return a }
This algorithm uses the properties of the array: numbers from 1 to n, and changes the sign of the element at the index corresponding to the value of the number. If the element is already negative, it means the number appears a second time, and we add it to the result. This approach works in O(n) time and O(1) additional space.