I have had a tough time with this problem on leetcode.
I've had to look up solutions because for some reason, my code would always end up having some issue. The current code I have, still loops infinitely when looking for a target number in the array that does not exist.
I am looking for some help on understanding if there is a more intuitive way to solve this problem and also help fixing my code.
I don't think I should need this line:
if nums[mid] == target or nums[low] == target or nums[high] == target:
return target
And am wondering what I can do to make sure that if I have an array with 1-3 numbers, that my code can find the target without having to specify this conditional statement. Here are a couple examples
print(search([1, 2, 3], 1))
print(search([1], 1))
print(search([2, 1], 1))
Also, with an example like this print(search([5, 1, 2, 3, 4], 6))
my code never returns -1
def search(nums, target):
low = 0
high = len(nums)-1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target or nums[low] == target or nums[high] == target:
return target
if nums[mid] <= nums[high]:
if target > nums[mid] and target <= nums[high]:
low = mid + 1
else:
high = mid - 1
elif nums[mid] > nums[low]:
if target >= nums[low] and target < nums[mid]:
high = mid - 1
else:
low = mid+1
return -1
print(search([1, 2, 3], 1))
print(search([5, 4, 1, 2, 3], 2))
print(search([3, 4, 5, 1, 2], 2))
print(search([1], 1))
print(search([2, 1], 1))
print(search([5, 1, 2, 3, 4], 6))
From coming across multiple solutions similar to the one I have above, people are saying it is O(logn)
but I don't understand how when we are moving our low
and high
by 1. This makes me believe that the solution is worst case O(n)
Looking for some help!
return target
when you should be returning the index of target. – Chucklow
andhigh
by 1. You are moving it 1 point from the middle (since you have already tested thatmiddle
does not contain the correct value). Thus, in each step, you are cutting half of the search space, making itO(log n)
. – Cecrops