Binary search: only 1 while loop (Python)

  • 0

    I saw most people had to find the index where the array was rotated first. So I want to give you another solution where you just simply do binary search once.

    class Solution(object):
        def search(self, nums, target):
            l = 0; r = len(nums)-1
            while l < r:
                m = (l+r)/2
                if nums[l] <= target and target <= nums[m]: r = m
                elif nums[m+1] <= target and target <= nums[r]: l = m+1
                elif nums[l] > nums[m]: r = m
                else: l = m+1
            if nums[l] == target: return l        
            return -1

Log in to reply

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