耐心和持久胜过激烈和狂热。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
根据题意,找出数组中第一个重复的数字并返回。本文使用 Go 语言去实现算法。
func findRepeatNumber(nums []int) int {mp := make(map[int]struct{})res := -1for _, num := range nums {if _, ok := mp[num]; ok {res = numbreak}mp[num] = struct{}{}}return res
}
时间复杂度:O(N),切片遍历需要 0(N) 的时间复杂度,将元素添加至 set
集合操作需要 O(1) 的时间复杂度。
空间复杂度:O(N),使用 map 创建 set 集合需要 O(N) 的空间复杂度。
index
。nums[1] = 1
),遍历下一个元素nums[4] = 1
) 等于对应下标值的元素(假设 nums[1] = 1
),则说明数字重复了,返回结果func findRepeatNumber(nums []int) int {index := 0for index < len(nums) {if nums[index] == index {index ++continue}if nums[nums[index]] == nums[index] {return nums[index]}nums[nums[index]], nums[index] = nums[index], nums[nums[index]]}return -1
}
时间复杂度:O(N),切片遍历需要 0(N) 的时间复杂度,交换元素操作需要 O(1) 的时间复杂度。
空间复杂度:O(1),没有使用额外的内存空间。
如果本文对你有帮助,欢迎点赞收藏加关注,如果本文有错误的地方,欢迎指出!
下一篇:yum命令应用