Problem Description:
Given an n + 1 contains an integer array nums, which are digital (including 1 and n), found that the presence of at least one repeating integer between 1 to n. Assuming that only a unique integer, find the number of repeats.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Description:
You can not change the original array (assuming that the array is read-only).
Only use extra space O (1) is.
It is less than the time complexity of O (n2).
Only a duplicate array of numbers, but it may be repeated more than once.
Code:
class Solution: def findDuplicate(self, nums: List[int]) -> int: l,r=0,len(nums)-1 while l<=r: if nums[l] != nums[nums[l]-1]: nums[nums[l]-1],nums[l]=nums[l],nums[nums[l]-1] else: l+=1 for i in range(len(nums)): if i+1 != nums[i]: return nums[i]
result: