数组题---5. 数组中重复的数字(287. Find the

2020-02-24  本文已影响0人  景景景景景景景色分明

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Input: [1,3,4,2,2]
Output: 2

1.You must not modify the array (assume the array is read only).

  1. You must use only constant, O(1) extra space.
  2. Your runtime complexity should be less than O(n2).
  3. There is only one duplicate number in the array, but it could be repeated more than once.

要求1、2,所以不能排序。

方法1. count

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        for i in range(len(nums)):
            if nums.count(nums[i])>1:
                return(nums[i])

很简单,但是表现不好。
Runtime: 4368 ms, faster than 5.15% of Python3 online submissions for Find the Duplicate Number.
Memory Usage: 15.2 MB, less than 17.86% of Python3 online submissions for Find the Duplicate Number.

方法2. 用链表

class Solution(object):
    def findDuplicate(self, nums):
        slow = 0
        fast = 0
        while True:
            fast = nums[nums[fast]]
            slow = nums[slow]
            if slow == fast:
                break
        slow = 0
        while slow != fast:
            slow = nums[slow]
            fast = nums[fast]
        return slow

Runtime: 56 ms, faster than 98.62% of Python3 online submissions for Find the Duplicate Number.
Memory Usage: 15.2 MB, less than 17.86% of Python3 online submissions for Find the Duplicate Number.

上一篇下一篇

猜你喜欢

热点阅读