[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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步