Leetcode 287, Find the Duplicate Number

本文介绍两种寻找数组中重复数字的方法:一是利用二分查找优化搜索范围;二是采用类似链表循环检测的技巧定位重复项。文章针对特定条件,如只读数组及常数级额外空间需求,提供高效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

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

 

最容易想到的思路是新开一个长度为n的全零list p[1~n]。依次从nums里读出数据,假设读出的是4, 就将p[4]从零改成1。如果发现已经是1了,那么这个4就已经出现过了,所以他就是重复的那个数。这个解法的时间复杂度是O(N)。但是由于本题要求空间复杂度是O(1)。所以不能用。

 

可以用二分法,low = 1, high = n, mid = (left + right)//2,如果<=mid 的元素个数 > mid,那么重复的数字一定在[1, mid]区间内。反之,则一定在[mid+1, high]里面。注意红色的>mid不能是>=。

例如 【1,2, 2, 3(mid), 4, 5, 6】,【1,2, 3, 3(mid), 4, 5】

 1 class Solution(object):
 2     def findDuplicate(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         left = 1
 8         right = len(nums) - 1
 9         
10         while left < right:
11             mid = (left + right)//2
12             count = 0
13             for x in nums:
14                 if x <= mid:
15                     count += 1
16             
17             if count > mid:
18                 right = mid 
19             else:
20                 left = mid + 1
21         
22         return left

第二种解法来自:http://www.cnblogs.com/grandyang/p/4843654.html

使用类似Linked List Cycle II的思路。

 1 def findDuplicate(self, nums):
 2         """
 3         :type nums: List[int]
 4         :rtype: int
 5         """
 6         slow = 0
 7         fast = 0
 8         t = 0
 9         while True:
10             slow = nums[slow]
11             fast = nums[nums[fast]]
12             if slow == fast:
13                 break
14         while True:
15             slow = nums[slow]
16             t = nums[t]
17             if slow == t:
18                 break
19         return slow        

 

转载于:https://www.cnblogs.com/lettuan/p/6186351.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值