代码拉取完成,页面将自动刷新
# Time: O(n)
# Space: O(1)
class Solution(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# Treat each (key, value) pair of the array as the (pointer, next) node of the linked list,
# thus the duplicated number will be the begin of the cycle in the linked list.
# Besides, there is always a cycle in the linked list which
# starts from the first element of the array.
slow = nums[0]
fast = nums[nums[0]]
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]
fast = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
# Time: O(nlogn)
# Space: O(1)
# Binary search method.
class Solution2(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 1, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
# Get count of num <= mid.
count = 0
for num in nums:
if num <= mid:
count += 1
if count > mid:
right = mid - 1
else:
left = mid + 1
return left
# Time: O(n)
# Space: O(n)
class Solution3(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
duplicate = 0
# Mark the value as visited by negative.
for num in nums:
if nums[abs(num) - 1] > 0:
nums[abs(num) - 1] *= -1
else:
duplicate = abs(num)
break
# Rollback the value.
for num in nums:
if nums[abs(num) - 1] < 0:
nums[abs(num) - 1] *= -1
else:
break
return duplicate
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。