Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 8b7a14f

Browse files
authored
Add files via upload
1 parent 43aed13 commit 8b7a14f

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# 704. Binary Search
2+
3+
Difficulty: easy
4+
Done: Yes
5+
Last edited: February 12, 2022 5:53 PM
6+
Link: https://leetcode.com/problems/binary-search/
7+
Topic: binary search
8+
9+
# Problem
10+
11+
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`.
12+
13+
# Solution
14+
15+
goal of the algorithm is to divide array in half, if our `target` is smaller than current then we take the left side of the array, if `target` is larger than the *current* then we take the right side of the array. Repeat
16+
17+
# Whiteboard
18+
19+
![target = 9](704%20Binary%20Search%20406000777e5f4354a1e4eb947aa1d4c1/Screen_Shot_2022-02-12_at_5.36.32_PM.png)
20+
21+
target = 9
22+
23+
![target = 2 (not existing)](704%20Binary%20Search%20406000777e5f4354a1e4eb947aa1d4c1/Screen_Shot_2022-02-12_at_5.36.49_PM.png)
24+
25+
target = 2 (not existing)
26+
27+
# Code
28+
29+
```python
30+
class Solution:
31+
def search(self, nums: List[int], target: int) -> int:
32+
33+
try:
34+
i = nums.index(target)
35+
except:
36+
i = -1
37+
38+
return i
39+
```
40+
41+
```python
42+
class Solution:
43+
def search(self, nums: List[int], target: int) -> int:
44+
# iteratively
45+
46+
left = 0
47+
right = len(nums) - 1
48+
while left <= right:
49+
middle = left + (right-left) // 2
50+
51+
if nums[middle] == target:
52+
return middle
53+
54+
if target < nums[middle]:
55+
# use left side
56+
right = middle - 1
57+
58+
if target > nums[middle]:
59+
# use right side
60+
left = middle + 1
61+
62+
return -1
63+
64+
```

0 commit comments

Comments
 (0)