Golang solution O(n) time,


  • 0
    S

    The idea is to place numbers in a way such that nums[i] = i+1. After the swap, iterate the nums to find positions that violate the rule.

    func findDisappearedNumbers(nums []int) []int {
        i := 0
        for i < len(nums) {
            if nums[i] != i + 1 && nums[nums[i]-1] != nums[i]{
                tmp := nums[nums[i]-1]
                nums[nums[i]-1] = nums[i]
                nums[i] = tmp
            } else {
                i += 1 
            }
        }
        res := make([]int, 0)
        for i, _ := range nums {
            if nums[i] != i+1 {
                res = append(res, i+1)
            }
        }
        return res
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.