为了能到远方,脚下的每一|

Dancing-Pierre

园龄:1年10个月粉丝:3关注:0

[Golang]力扣Leetcode - 448. 找到所有数组中消失的数字(哈希)

[Golang]力扣Leetcode - 448. 找到所有数组中消失的数字(哈希)

题目:给你一个含 n 个整数的数组 nums ,其中 nums[i] 在区间 [1, n] 内。请你找出所有在 [1, n] 范围内但没有出现在 nums 中的数字,并以数组的形式返回结果。

链接力扣Leetcode - 448. 找到所有数组中消失的数字.

示例 1:

输入:nums = [4,3,2,7,8,2,3,1]
输出:[5,6]

示例 2:

输入:nums = [1,1]
输出:[2]

思路:使用哈希表,遍历数组把出现过的数存在哈希表中。再遍历哈希表,把没有存在哈希表中的数存进数组即可。

Go代码:

package main
import "fmt"
func findDisappearedNumbers(nums []int) []int {
HashMap := map[int]int{}
var res []int
for _, i := range nums {
HashMap[i] = 1
}
for j := 1; j <= len(nums); j++ {
if HashMap[j] != 1 {
res = append(res, j)
}
}
return res
}
func main() {
a := []int{4, 3, 2, 7, 8, 2, 3, 1}
fmt.Println(findDisappearedNumbers(a))
}

提交截图
在这里插入图片描述

本文作者:Dancing-Pierre

本文链接:https://www.cnblogs.com/wyc-1009/p/17548078.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Dancing-Pierre  阅读(6)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起