Skip to content

Commit b427cdc

Browse files
committed
Add solution #34
1 parent 886ad35 commit b427cdc

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
28|[Implement strStr()](./0028-implement-strstr.js)|Easy|
3131
31|[Next Permutation](./0031-next-permutation.js)|Medium|
3232
33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium|
33+
34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium|
3334
35|[Search Insert Position](./0035-search-insert-position.js)|Easy|
3435
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
3536
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 34. 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+
* Difficulty: Medium
5+
*
6+
* Given an array of integers nums sorted in non-decreasing order, find the starting and
7+
* ending position of a given target value.
8+
*
9+
* If target is not found in the array, return [-1, -1].
10+
*
11+
* You must write an algorithm with O(log n) runtime complexity.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @param {number} target
17+
* @return {number[]}
18+
*/
19+
var searchRange = function(nums, target) {
20+
let start = 0;
21+
let end = nums.length - 1;
22+
23+
while (start <= end) {
24+
const middle = Math.floor((start + end) / 2);
25+
if (target > nums[middle]) {
26+
start = middle + 1;
27+
} else {
28+
end = middle - 1;
29+
}
30+
}
31+
32+
if (nums[start] !== target) {
33+
return [-1, -1];
34+
}
35+
36+
while (nums[start - 1] === target) start--;
37+
while (nums[end + 1] === target) end++;
38+
39+
return [start, end];
40+
};

0 commit comments

Comments
 (0)