Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit bb509ef

Browse files
committed
[20230501] Solve Binary Search problems
1 parent 2166db0 commit bb509ef

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# 2089. Find Target Indices After Sorting Array
2+
# https://leetcode.com/problems/find-target-indices-after-sorting-array/
3+
4+
from typing import List
5+
6+
7+
class Solution:
8+
def targetIndices(self, nums: List[int], target: int) -> List[int]:
9+
m_cnt = 0
10+
t_cnt = 0
11+
12+
for num in nums:
13+
if num < target:
14+
m_cnt += 1
15+
if num == target:
16+
t_cnt += 1
17+
18+
result = []
19+
for i in range(t_cnt):
20+
result.append(m_cnt + i)
21+
22+
return result
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# 852. Peak Index in a Mountain Array
2+
# https://leetcode.com/problems/peak-index-in-a-mountain-array/description/
3+
4+
from typing import List
5+
6+
7+
class Solution:
8+
def peakIndexInMountainArray(self, arr: List[int]) -> int:
9+
start, end = 0, len(arr) - 1
10+
while start <= end:
11+
mid = (start + end) // 2
12+
if arr[mid - 1] < arr[mid] and arr[mid + 1] < arr[mid]:
13+
return mid
14+
if arr[mid-1] < arr[mid]:
15+
start = mid
16+
else:
17+
end = mid
18+
return 0
19+
20+
21+
if __name__ == '__main__':
22+
sol = Solution()
23+
# print(sol.peakIndexInMountainArray([3, 4, 5, 1]))
24+
# print(sol.peakIndexInMountainArray([3, 5, 3, 2, 0]))
25+
print(sol.peakIndexInMountainArray([24, 69, 100, 99, 79, 78, 67, 36, 26, 19]))
26+
print(sol.peakIndexInMountainArray([8, 18, 24, 31, 37, 42, 43, 56, 65, 73, 93, 98, 100, 98, 76, 72, 69, 24, 23]))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /