| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | |||||
| 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 10 | 11 | 12 | 13 | 14 | 15 | 16 |
| 17 | 18 | 19 | 20 | 21 | 22 | 23 |
| 24 | 25 | 26 | 27 | 28 | 29 | 30 |
| 31 |
Tags
- nlp
- Python3
- 파이썬
- SQL
- two-pointer
- graph
- Stack
- 생성형AI
- Python
- 파이썬알고리즘
- GenerativeAI
- codeup
- BFS
- 니트코드
- 릿코드
- Greedy
- 투포인터
- GenAI
- 슬라이딩윈도우
- stratascratch
- 리트코드
- dfs
- 코드업
- 알고리즘
- sql코테
- LeetCode
- heap
- binary Tree
- array
- tree
Archives
- Today
- Total
Tech for good
[Neetcode/Array, Binary Search] Binary Search 본문

1. Linear Search
class Solution:
def search(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if target == nums[i]:
return i
return -1
- Time Complexity: O(n)
2. Binary Search
Binary Search, Tree -> Narrow down the scope w/ starter, end and middle!
There are two ways for a Binary Search.
1. Two pointer + while loop
2. Recursion
2.1. Two pointer + while loop
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
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
- Time Complexity: O(logn)
2.2. Recursion
- call function in the funcion
- add helper() function
class Solution:
def search(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums)-1
def helper(start, end):
# base case
if start == end:
if target == nums[end]:
return end
else:
return -1 # if target does not exist in the list, return -1
middle = (start + end) // 2
if target <= nums[middle]:
return helper(start, middle)
else:
return helper(middle+1, end)
return helper(start, end)
- Time Complexity: O(logn)
'IT > Computer Science' 카테고리의 다른 글
| [Leetcode/Tree, DFS, Binary Tree, Recursion] 226. Invert Binary Tree (0) | 2025.07.23 |
|---|---|
| [Codepath/Array, Binary Search] Bad Product (0) | 2025.07.22 |
| [Leetcode/Linked List, Hash Table] 3063. Linked List Frequency (0) | 2025.07.13 |
| [Leetcode/Linked List]83. Remove Duplicates from Sorted List (0) | 2025.07.12 |
| [Neetcode/Linked List] Reorder Linked List (1) | 2025.07.10 |