Skip to content

Commit 50f50e7

Browse files
xfrnk2yunyeongkim
authored andcommitted
ccf05017 - week17 (34.Permutation)
* beomseok - week17 34 * typo: Problem num & url
1 parent 2869301 commit 50f50e7

File tree

1 file changed

+38
-0
lines changed
  • LeetCode-Problems/34.Find_First_and_Last_Position_of_Element_in_Sorted_Array

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
### Problem
2+
[34. Find First and Last Position of Element in Sorted Array]([https://leetcode.com/problems/search-insert-position](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array)
3+
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
4+
### Solution
5+
1. Perform two modified binary searches
6+
2. One that always moves the right boundary leftward upon seeing target (to find the first occurrence).
7+
3. One that always moves the left boundary rightward upon seeing target (to find the last occurrence).
8+
4. Call this routine twice—once with findFirst = True, once with findFirst = False.
9+
5. The two results give [first_index, last_index].
10+
11+
### Code
12+
```python
13+
class Solution:
14+
def binary_search(self, nums: List[int], target: int, findFirst: bool) -> int:
15+
16+
start, end = 0, len(nums) - 1
17+
result = -1
18+
19+
while start <= end:
20+
mid = (start + end) // 2
21+
if nums[mid] == target:
22+
result = mid
23+
if findFirst:
24+
end = mid - 1
25+
else:
26+
start = mid + 1
27+
elif nums[mid] < target:
28+
start = mid + 1
29+
else:
30+
end = mid - 1
31+
32+
return result
33+
34+
def searchRange(self, nums: List[int], target: int) -> List[int]:
35+
first_pos = self.binary_search(nums, target, True)
36+
last_pos = self.binary_search(nums, target, False)
37+
return [first_pos, last_pos]
38+
```

0 commit comments

Comments
 (0)