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 bb549a6

Browse files
find-first-and-last-position-of-element-in-sorted-array
1 parent fba5115 commit bb549a6

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number[]}
5+
*/
6+
var searchRange = function (nums, target) {
7+
let range = [-1, -1];
8+
let left = extremeInsertionIndex(nums, target, true);
9+
if(left == nums.length || nums[left] != target){
10+
return range;
11+
}
12+
range[0] = left;
13+
range[1] = extremeInsertionIndex(nums, target, false) - 1;
14+
return range;
15+
};
16+
17+
const extremeInsertionIndex = function (nums, target, left) {
18+
let low = 0, high = nums.length;
19+
while (low < high) {
20+
let middle = Math.floor((low + high) / 2);
21+
if (nums[middle] > target || (left && target == nums[middle])) {
22+
high = middle;
23+
} else {
24+
low = middle + 1;
25+
}
26+
}
27+
return low;
28+
}
29+
30+
console.log(searchRange([5,7,7,8,8,10],5))
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Find First and Last Position of Element in Sorted Array
2+
3+
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
4+
5+
Your algorithm's runtime complexity must be in the order of O(log n).
6+
7+
If the target is not found in the array, return [-1, -1].
8+
9+
## Example 1
10+
11+
Input: nums = [5,7,7,8,8,10], target = 8
12+
13+
Output: [3,4]
14+
15+
## Example 2
16+
17+
Input: nums = [5,7,7,8,8,10], target = 6
18+
19+
Output: [-1,-1]
20+
21+
## More Info
22+
23+
<https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/>

0 commit comments

Comments
(0)

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