상위 150개 인터뷰쉬움

이진 검색

'이진 검색' 문제에 대한 자세한 가이드 및 Python 구현입니다.

문제 설명

쉬움

오름차순으로 정렬된 정수 배열 nums과 정수 target이 주어지면 nums에서 target을 검색하는 함수를 작성하세요. target이 존재하면 해당 인덱스를 반환합니다. 그렇지 않으면 -1를 반환합니다.

O(log n) 런타임 복잡도를 갖는 알고리즘을 작성해야 합니다.

search(nums: List[int], target: int) -> int 함수를 작성하세요.

제약
  • 1 <= len(nums) <= 10^4
  • -10^4 < nums[i], target < 10^4
  • All integers in nums are unique
  • nums is sorted in ascending order

Example 1
Input
nums = [-1, 0, 3, 5, 9, 12], target = 9
Output
4
Explanation

9 exists in nums and its index is 4.

Example 2
Input
nums = [-1, 0, 3, 5, 9, 12], target = 2
Output
-1
Explanation

2 does not exist in nums so return -1.

Need a Hint?
세트나 힙과 같은 이진 검색 관련 데이터 구조를 사용하는 것을 고려해보세요.
Edge Cases to Watch
  • 빈 입력 구조
  • 단일 요소 입력
  • 큰 수치 범위

해결할 준비가 되셨나요?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

편집기에서 열기
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

권장 Python 리소스

관련 대화형 튜토리얼, 치트 시트, 코드 비교를 통해 지식을 확장하세요.