[LeetCode By Go 21]448. Find All Numbers Disappeared in an Array

题目

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]

解题思路

将nums[i]置换到其对应的位置nums[nums[i]-1]上去,比如对于没有缺失项的正确的顺序应该是[1, 2, 3, 4, 5, 6, 7, 8],而我们现在却是[4,3,2,7,8,2,3,1],我们需要把数字移动到正确的位置上去,比如第一个4就应该和7先交换个位置,以此类推,最后得到的顺序应该是[1, 2, 3, 4, 3, 2, 7, 8],我们最后在对应位置检验,如果nums[i]和i+1不等,那么我们将i+1存入结果res中即可

代码

findDisappearedNumbers.go

package _448_Find_All_Numbers_Disappeared_in_an_Array

func FindDisappearedNumbers(nums []int) []int {
    var ret []int
    length := len(nums)

    for i := 0; i < length; i++ {
        if nums[i] != nums[nums[i] - 1] {
            nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]
            i--
        }
    }

    for i := 0; i < length; i++ {
        if (i + 1) != nums[i] {
            ret = append(ret, (i+1))
        }
    }

    return ret
}

测试

findDisappearedNumbers_test.go

package _448_Find_All_Numbers_Disappeared_in_an_Array

import "testing"

func sliceEqual(want, ret []int) bool {
    len1 := len(want)
    len2 := len(ret)

    if len1 != len2 {
        return false
    }

    for i := 0; i < len1; i++ {
        if want[i] != ret[i] {
            return false
        }
    }

    return true
}

func TestFindDisappearedNumbers(t *testing.T) {
    input := []int{4,3,2,7,8,2,3,1}
    want := []int{5,6}

    ret := FindDisappearedNumbers(input)

    ok := sliceEqual(want, ret)
    if ok {
        t.Logf("pass")
    } else {
        t.Errorf("fail, want %+v, get %+v", want, ret)
    }
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/1766dfbe06c4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞