Advertisement
jinhuang1102

287. Find the Duplicate Number

Jan 14th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. """
  2. Though the values are not ordered, the indices are still ordered. That's why binary search can still be used. Very interesting solution.
  3. https://leetcode.com/problems/find-the-duplicate-number/discuss/72844/Two-Solutions-(with-explanation):-O(nlog(n))-and-O(n)-time-O(1)-space-without-changing-the-input-array
  4. """
  5. class Solution:
  6.     def findDuplicate(self, nums):
  7.         """
  8.        :type nums: List[int]
  9.        :rtype: int
  10.        """
  11.         left = 0
  12.         right = len(nums) - 1
  13.        
  14.         while left < right:
  15.             mid = (left + right) // 2
  16.            
  17.             cont = 0
  18.             for num in nums:
  19.                 if num <= mid:
  20.                     cont += 1
  21.                    
  22.             if cont <= mid:
  23.                 left = mid + 1
  24.             else:
  25.                 right = mid
  26.                
  27.         return right
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement