https://leetcode.com/problems/binary-search/
Binary Search - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이 과정
이진 탐색으로 target이 배열에 존재하면 target의 index를, 아니면 -1을 출력하는 문제이다.
배열이 정렬된 상태로 들어오므로 이진 탐색으로 탐색 범위를 반씩 줄여나가면서 target을 빠르게 찾을 수 있다.
소스 코드
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
mid = (left + right) // 2
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 349. Intersection of Two Arrays [Python] (0) | 2022.11.10 |
---|---|
LeetCode - 33. Search in Rotated Sorted Array [Python] (0) | 2022.11.10 |
LeetCode - 973. K Closest Points to Origin [Python] (0) | 2022.10.20 |
LeetCode - 179. Largest Number [Python] (0) | 2022.10.20 |
LeetCode - 56. Merge Intervals [Python] (0) | 2022.10.17 |