알고리즘/2. Binary Search
[Python][leetcode 704. Binary Search] basic problem
bay07
2024. 3. 7. 17:14
📕 Problem
https://leetcode.com/problems/binary-search/
💡 My Solution
This is very basic problem for binary search method.
# leetcode
# 704. Binary Search
# nums = [-1,0,3,5,9,12]
# target = 9
nums = [-1,0,3,5,9,12]
target = 9
# sort the list first
nums.sort()
star = 0
end = len(nums) - 1
flag = 0
index = 0
while True:
mid = (star + end)//2
if nums[mid] == target:
flag = 1
index = mid
break
elif nums[mid] > target:
end = mid - 1
else:
star = mid + 1
if end < star:
flag = 0
break
if flag == 0:
# target does not exist
print(-1)
else:
print(f"{nums[mid]} exists in nums and its index is {index}")
✔️ TIL (Today I learned)
Becuase I practiced binary search a lot before. This problem was not difficult. Practice makes perfect. Also It was very helpful to write down and draw the process of algorithm.
💻 Answer
▷ Final code
더보기
class Solution(object):
def search(self, nums, target):
# sort the list first
nums.sort()
star = 0
end = len(nums) - 1
flag = 0
index = 0
while True:
mid = (star + end)//2
if nums[mid] == target:
flag = 1
index = mid
break
elif nums[mid] > target:
end = mid - 1
else:
star = mid + 1
if end < star:
flag = 0
break
if flag == 0:
# target does not exist
return - 1
else:
# target exist
return index