Python Binary Search


  • 0
    H
    class Solution(object):
        def singleNonDuplicate(self, nums):
            l,r = 0,len(nums)-1
            mid = (l+r)/2
            while l <= r:
                mid = (l+r)/2
                if mid - 1 > -1 and nums[mid] == nums[mid-1]:
                    if (mid-l)%2: l = mid + 1
                    else: r = mid - 2
                elif mid + 1 < len(nums) and nums[mid] == nums[mid+1]:
                    if (mid-l)%2: r = mid - 1
                    else: l = mid + 2
                else:
                    return nums[mid]
            return nums[mid]
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.