File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 0704. Binary Search
2
+
3
+ * Difficulty: easy
4
+ * Link: https://leetcode.com/problems/binary-search/
5
+ * Topics: Binary-Search
6
+
7
+ # Clarification
8
+
9
+ 1 . Check the inputs and outputs
10
+ - INPUT: List[ int]
11
+ - OUTPUT: index of list
12
+ 2 . Check the main goal
13
+ - the list is sorted
14
+ - time complexity in O(log n)
15
+
16
+ # Naive Solution
17
+
18
+ ### Thought Process
19
+
20
+ - 建立兩個指標
21
+ - left pointer: 陣列開頭的位置、值的下限)
22
+ - right pointer: 陣列結束的位置、值的上限
23
+ 1 . 找中間指標對應的值
24
+ - = target ⇒ return
25
+ - < target ⇒ 調高下限 left pointer ++
26
+ - > target ⇒ 調低上限 right pointer - -
27
+ - Implement
28
+
29
+ ``` python
30
+ class Solution :
31
+ def search (self , nums : List[int ], target : int ) -> int :
32
+ left = 0
33
+ right = len (nums) - 1
34
+ while left <= right:
35
+ mid = int ((left + right) / 2 )
36
+ if nums[mid] == target:
37
+ return mid
38
+ if nums[mid] < target:
39
+ left += 1
40
+ elif nums[mid] > target:
41
+ right -= 1
42
+ return - 1
43
+ ```
44
+
45
+
46
+ # ## Complexity
47
+
48
+ - Time complexity: O(log n)
49
+ - Space complexity: O(1 )
50
+
51
+ # Reference
52
+
53
+ - **** [初學者學演算法|從時間複雜度認識常見演算法](https:// medium.com/ appworks- school/% E5% 88 % 9D % E5% AD % B8% E8% 80 % 85 % E5% AD % B8% E6% BC % 94 % E7% AE % 97 % E6% B3% 95 -% E5% BE % 9E % E6% 99 % 82 % E9% 96 % 93 % E8% A4% 87 % E9% 9B % 9C % E5% BA % A6% E8% AA % 8D % E8% AD % 98 % E5% B8% B8% E8% A6% 8B % E6% BC % 94 % E7% AE % 97 % E6% B3% 95 -% E4% B8% 80 - b46fece65ba5)****
You can’t perform that action at this time.
0 commit comments