Given an array of integers nums
which is sorted in ascending order, and an integer target
, write a function to search target
in nums
. If target
exists, then return its index. Otherwise, return -1
.
You must write an algorithm with O(log n)
runtime complexity.
์ ๋ ฌ๋ nums
๋ฅผ ์
๋ ฅ๋ฐ์ ์ด์ง ๊ฒ์์ผ๋ก target์ ํด๋น๋๋ ์ธ๋ฑ์ค๋ฅผ ์ฐพ์๋ผ.
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
while left<=right:
mid=left + (right-left)//2
if target==nums[mid]:
return mid
# If x is greater, ignore left half
elif target>nums[mid]:
left = mid+1
# If x is greater, ignore right half
else:
right = mid-1
return -1
There is TWO ways to implement Binary Search.
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums)-1
def dfs(nums, l, r, target):
if l<=r:
mid=l+(r-l)//2
if target==nums[mid]:
return mid
# If element is smaller than mid, then it
# can only be present in left subarray
elif target>nums[mid]:
dfs(arr, mid+1, r, target)
# Else the element can only be present
# in right subarray
else:
dfs(arr, l, mid-1, target)
else:
return -1
My solution was "Iterative" implementation for Binary Search.
bisect()
- ๋ชจ๋ ์ฌ์ฉํ์ด์ฌ์์๋ ์ด์ง ๊ฒ์์ ์ง์ ๊ตฌํํ ํ์๊ฐ ์๋ค. ์ด์ง ๊ฒ์ ์๊ณ ๋ฆฌ์ฆ์ ์ง์ํ๋ bisect
๋ชจ๋์ ๊ธฐ๋ณธ์ ์ผ๋ก ์ ๊ณตํ๋ค.
class Solution:
def search(self, nums: List[int], target: int) -> int:
index = bisect.bisect(nums, target)
if index<len(nums) and nums[index]==target:
return index
else:
return -1
bisect()
์ ๋ ฌ๋ ๋ฆฌ์คํธ์ ์๋ก์ด ์์ดํ
์ฝ์
ํ์ ๋ค์ ์ ๋ ฌํ ํ์ ์๋๋ก ๊ด๋ฆฌํ ์ ์๋๋ก ์ง์ํ๋ ๋ชจ๋์ด๋ค.
๊ธฐ๋ณธ์ ์ธ ์ด์ง ๋ถํ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ bisect
๋ผ๊ณ ๋ถ๋ฆฐ๋ค.
bisect.bisect_left( )
์ ๋ ฌ๋ a์ x๋ฅผ ์ฝ์
ํ ์์น, ์ข์ธก์ผ๋ก ์ฝ์
๋๋ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๋ค.
์ฐพ์๋ธ ๊ฐ์ ํด๋น ์์น ์ธ๋ฑ์ค๋ฅผ ๋ฆฌํด
bisect.bisect_right( )
, bisect.bisect_right( )
์ ๋ ฌ๋ a์ x๋ฅผ ์ฝ์
ํ ์์น, ์ข์ธก์ด ์๋ ์ฐ์ธก์ผ๋ก ์ฝ์
๋๋ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๋ค.
์ฐพ์๋ธ ๊ฐ์ ๋ค์ ์ธ๋ฑ์ค๋ฅผ ๋ฆฌํด
References
- https://leetcode.com/problems/binary-search/
- https://www.code-recipe.com/post/binary-search
- https://www.geeksforgeeks.org/binary-search/
- https://docs.python.org/ko/3/library/bisect.html
- ํ์ด์ฌ ์๊ณ ๋ฆฌ์ฆ ์ธํฐ๋ทฐ(95๊ฐ์ง ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด๋ก ์์ฑํ๋ ์ฝ๋ฉ ํ ์คํธ), ๋ฐ์๊ธธ ์ง์
- https://wikidocs.net/105425