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 8806412

Browse files
Create Find First and Last Position of Element in Sorted Array
1 parent defa303 commit 8806412

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
想法:用 binary search 找出第一個出現的位置跟最後一個出現的位置即可,沒有找到則輸出 {-1 , -1}
2+
第一個出現的位置:相等時維護右界相同(代表第一個出現的元素是包含現在看的以前)
3+
最後一個出現的位置:相等時維護左界相同(代表最後一個出現的元素是包含現在看的以後)
4+
5+
Time Complexity : O(logn) for binary search two times
6+
Space Complexity : O(1) for variables
7+
8+
class Solution {
9+
public:
10+
vector<int> searchRange(vector<int>& nums, int target) {
11+
// find the start position
12+
int l = 0 , r = nums.size() - 1 ;
13+
int start ;
14+
while (l < r) {
15+
int m = (l + r) / 2 ;
16+
if ( nums[m] > target )
17+
r = m - 1 ;
18+
else if ( nums[m] == target)
19+
r = m ;
20+
else
21+
l = m + 1 ;
22+
}
23+
if (nums.empty() || nums[l] != target)
24+
return {-1 , -1} ;
25+
else
26+
start = l ;
27+
28+
// find the end position
29+
l = 0 , r = nums.size() - 1 ;
30+
while (l < r) {
31+
int m = (l + r + 1) / 2 ;
32+
if (nums[m] > target)
33+
r = m - 1 ;
34+
else if (nums[m] == target)
35+
l = m ;
36+
else
37+
l = m + 1 ;
38+
}
39+
return {start , l} ;
40+
}
41+
};

0 commit comments

Comments
(0)

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