Skip to content

Commit c34ab9a

Browse files
committed
left right bound
1 parent 92720c4 commit c34ab9a

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Leetcode/0704.Binary-Search/README.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# [704. Binary Search](https://leetcode.com/problems/binary-search/)
2+
###### tags: `Easy` `Leetcode` `Binary Search`
23

34
## 題目
45

@@ -136,4 +137,63 @@ func BinarySearchRecursively(nums []int, target int, start int, end int) int {
136137
}
137138
}
138139

140+
// 有點類似 nums 小於 target的元素有幾個
141+
func LeftBound(nums []int, target int) (index int) {
142+
lenght := len(nums)
143+
if lenght <= 0 {
144+
return -1
145+
}
146+
left, right := 0, lenght-1
147+
148+
for left <= right {
149+
// 除以2
150+
// mid := left + (right-left)>>1
151+
mid := int(uint(right+left) >> 1)
152+
if nums[mid] == target {
153+
// 要繼續找左邊, 所以把右邊變小
154+
right = mid - 1
155+
} else if nums[mid] < target {
156+
// 找右邊
157+
left = mid + 1
158+
} else if nums[mid] > target {
159+
// 找左邊
160+
right = mid - 1
161+
}
162+
}
163+
// 都沒找到 注意: left越界情況
164+
if left >= lenght || nums[left] != target {
165+
return -1
166+
}
167+
return left
168+
}
169+
170+
func RightBound(nums []int, target int) (index int) {
171+
lenght := len(nums)
172+
if lenght <= 0 {
173+
return -1
174+
}
175+
left, right := 0, lenght-1
176+
177+
for left <= right {
178+
// 除以2
179+
// mid := left + (right-left)>>1
180+
mid := int(uint(right+left) >> 1)
181+
if nums[mid] == target {
182+
// 注意:要繼續找右邊, 所以把左邊變大=mid+1
183+
left = mid + 1
184+
} else if nums[mid] < target {
185+
// 找右邊
186+
left = mid + 1
187+
} else if nums[mid] > target {
188+
// 找左邊
189+
right = mid - 1
190+
}
191+
}
192+
// 都沒找到 注意:right越界情況
193+
if right < 0 || nums[right] != target {
194+
return -1
195+
}
196+
return right
197+
}
198+
139199
```

0 commit comments

Comments
 (0)