leetcode#287. Find the Duplicate Number

来源:互联网 发布:java服务器用linux 编辑:程序博客网 时间:2024/06/16 19:14

Description

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.

Note:

  • You must not modify the array (assume the array is read only).
  • You must use only constant, O(1) extra space.
  • Your runtime complexity should be less than O(n^2).
  • There is only one duplicate number in the array, but it could be repeated more than once.

Code

class Solution:    def findDuplicate(self, nums):        """        :type nums: List[int]        :rtype: int        """        Min, Max = 1, len(nums) - 1        return self.find(nums, Min, Max)    def find(self, nums, Min, Max):        while Min <= Max:            mid = (Min + Max) // 2            small = big = isMid = 0            for i in nums:                if i == mid:                    isMid += 1                    if isMid == 2:                        return mid                elif i > mid and i <= Max:                    big += 1                elif i >= Min and i < mid:                    small += 1            if small > big:                Max = mid - 1            elif small < big:                Min = mid + 1            else:                return self.find(nums, Min, mid - 1) or self.find(nums, mid + 1, Max)        return False

题目要求了时间复杂度和空间复杂度,那么我想到的也就是这个方法了,不断缩小检索的范围,直至找到重复的值。这个算法的时间复杂度应该是n*logn。

原创粉丝点击