leetcode287 Find the Duplicate Number

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode287 Find the Duplicate Number相关的知识,希望对你有一定的参考价值。

 1 """
 2 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.
 3 Example 1:
 4 Input: [1,3,4,2,2]
 5 Output: 2
 6 Example 2:
 7 Input: [3,1,3,4,2]
 8 Output: 3
 9 """
10 """
11 解法一:
12 这道题竟然可以用快慢指针法!!!
13 与leetcode142类似。https://www.cnblogs.com/yawenw/p/12324170.html
14 因此找环 找重复值 都可以考虑用快慢指针法
15 """
16 class Solution1:
17     def findDuplicate(self, nums):
18         if not nums:
19             return -1
20         slow = nums[0]
21         fast = nums[nums[0]]
22         while slow != fast:
23             slow = nums[slow]
24             fast = nums[nums[fast]]
25         fast = 0
26         while slow != fast:
27             fast = nums[fast]
28             slow = nums[slow]
29         return slow
30 
31 """
32 解法二:时间复杂度高的解法
33 """
34 class Solution2:
35     def findDuplicate(self, nums):
36         for i in range(len(nums)):
37             if nums[i] in nums[i+1:]:
38                 return nums[i]

 

以上是关于leetcode287 Find the Duplicate Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 287. Find the Duplicate Number(找重复数字)

[LeetCode] 287. Find the Duplicate Number

LeetCode 287. Find the Duplicate Number

<LeetCode OJ> 287. Find the Duplicate Number

[LeetCode] 287. Find the Duplicate Number 寻找重复数

LeetCode 287. Find the Duplicate Number (找到重复的数字)