287. Find the Duplicate Number
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.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
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(n^2).
4. There is only one duplicate number in the array, but it could be repeated more than once.
解法
1)先排序,然后遍历一次,如果有重复的数字一定会相邻出现。
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
排序的时间复杂度是 。
2)使用集合记录重复元素。
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
seen = {}
for num in nums:
if num in seen:
return num
seen.add(num)
时间复杂度 ,空间复杂度 。
3)快慢指针,参考寻找环形链表的入口节点。
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
slow = nums[0]
fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
ptr1 = nums[0]
ptr2 = slow
while ptr1 != ptr2:
ptr1 = nums[ptr1]
ptr2 = nums[ptr2]
return ptr1
时间复杂度 ,空间复杂度 。
引用
Last updated
Was this helpful?