[LeetCode By Go 68]645. Set Mismatch

题目

The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]

Note:

  1. The given array size will in the range [2, 10000].
  2. The given array’s numbers won’t have any order.

解题思路

先找到出现两次的数,再找到miss的数
遍历数组,将数和出现的次数放入map中,如果某个数出现了两次,则这个数就是重复的数。
遍历的同事计算数组值的和realSum,根据他和1到n的和sum的关系

missNum = repeatNum + (realSum – sum)

计算出miss的值

代码

func findErrorNums(nums []int) []int {
    var sum int
    var repeatNum int
    var missNum int
    var numMap map[int]int
    numMap = make(map[int]int)

    for _, v := range nums {
        numMap[v]++
        if 2 == numMap[v] {
            repeatNum = v
        }

        sum += v
    }

    len1 := len(nums)
    realSum := (len1 + 1) * len1 /2
    missNum = repeatNum + (realSum - sum)

    return []int{repeatNum, missNum}
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/281886b1ea71
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞