【Golang】LeetCode442Find All Duplicates in an Array

Given an array of integers a, wherein 1 ≤ a [i] ≤ n (n is the length of the array), in which some elements appear twice while other elements once.
Find all elements appear twice.
You do not have any extra space and solve this problem in a (n) time complexity O do?

Example:

输入:
[4,3,2,7,8,2,3,1]

输出:
[2,3]

Meaning of the questions: The key is to elements in the array as an index point of view on the line. If the index number is appeared once, gave -1 because only occurs twice, if the second again, the values corresponding to the position would be less than zero, on the line directly added to the result set. At first I thought once appeared -1 * -1 once again, this time finally traversed to find less than zero, but found some problems, there have been some numbers will not be manslaughter.

O (N) time, O (1) space

func findDuplicates(nums []int) []int {
    result := make([]int, 0)
    for _, v := range nums {
        v = int(math.Abs(float64(v)))
        if nums[v-1] > 0 {
            nums[v-1] = nums[v-1] * -1
        } else {
            result = append(result, v)
        }
    }
    return result
}

Guess you like

Origin blog.51cto.com/fulin0532/2432452