首页 > 编程语言 > 详细

数组中重复的数字

时间:2021-06-05 01:20:28      阅读:15      评论:0      收藏:0      [点我收藏+]

题目要求

找出数组中重复的数字。

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

实现

  1. 时间复杂度为O(1),空间复杂度为O(n)
class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        d = [0] * len(nums)
        for i in nums:
            if d[i] == 0:
                d[i] = 1
            else:
                return i
  1. 空间复杂度为O(1),时间复杂度为O(n)
class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        nums.sort()
        p = nums[0]
        n = len(nums)
        for index in range(1, n):
            if p== nums[index]:
                return p
            p= nums[index]

数组中重复的数字

原文:https://www.cnblogs.com/chengejie/p/14851471.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!