为了能到远方,脚下的每一步都不能少.|

Dancing-Pierre

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

[Golang]力扣Leetcode—剑指Offer—数组—03.数组中重复的数字(哈希表)

[Golang]力扣Leetcode—剑指Offer—数组—03.数组中重复的数字(哈希表)

题目:找出数组中重复的数字。

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

链接力扣Leetcode—剑指Offer—数组—03.数组中重复的数字.

示例 1:

输入:[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3

思路:一开始用两个 for 循环遍历,一下子就超时了,代码如下:

func findRepeatNumber(nums []int) int {
n := len(nums)
res := 0
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
if nums[i] == nums[j] {
res = nums[i]
break
} else {
continue
}
}
}
return res
}

简简单单超时:
在这里插入图片描述
后面遍历一下数组,用哈希表存储数字出现的次数,如果 >1 ,就输出那个 key 并跳出循环

Go代码如下:

package main
import "fmt"
func findRepeatNumber(nums []int) int {
m := make(map[int]int)
res := 0
for _, v := range nums {
m[v]++
}
for key, v := range m {
if v > 1 {
res = key
break
} else {
continue
}
}
return res
}
func main() {
a := []int{3, 4, 2, 0, 0, 1}
fmt.Println(findRepeatNumber(a))
}

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

本文作者:Dancing-Pierre

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

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

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