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 11a5a71

Browse files
Add easier to follow solution for 34.
1 parent 580b1cb commit 11a5a71

File tree

1 file changed

+33
-19
lines changed

1 file changed

+33
-19
lines changed

‎solutions/0034.find-first-and-last-position-of-element-in-sorted-array.js

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,47 @@
44
* @return {number[]}
55
*/
66
var searchRange = function (nums, target) {
7-
letfirstMatch = binarySearch(nums,0,nums.length-1, target);
7+
constout = [-1, -1];
88

9-
if (firstMatch === -1) return [-1, -1];
9+
out[0] = getFirst(nums, target);
10+
out[1] = getLast(nums, target);
1011

11-
let i = firstMatch,
12-
j = firstMatch;
13-
while (i > -1 && nums[i - 1] === target) {
14-
i--;
15-
}
16-
while (j < nums.length - 1 && nums[j + 1] === target) {
17-
j++;
18-
}
19-
20-
return [i, j];
12+
return out;
2113
};
2214

23-
const binarySearch = function (nums, left, right, target) {
24-
while (left <= right) {
25-
const mid = Math.floor((left + right) / 2);
26-
if (nums[mid] === target) {
15+
var getFirst = function (nums, target) {
16+
var lo = 0,
17+
hi = nums.length - 1;
18+
while (lo <= hi) {
19+
let mid = Math.floor((lo + hi) / 2);
20+
21+
if (target === nums[mid] && (mid === 0 || nums[mid - 1] < target)) {
2722
return mid;
23+
} else if (target > nums[mid]) {
24+
lo = mid + 1;
25+
} else {
26+
hi = mid - 1;
2827
}
28+
}
2929

30-
if (nums[mid] < target) {
31-
left = mid + 1;
30+
return -1;
31+
};
32+
33+
var getLast = function (nums, target) {
34+
var lo = 0,
35+
hi = nums.length - 1;
36+
while (lo <= hi) {
37+
let mid = Math.floor((lo + hi) / 2);
38+
39+
if (
40+
target === nums[mid] &&
41+
(mid === nums.length - 1 || nums[mid + 1] > target)
42+
) {
43+
return mid;
44+
} else if (target < nums[mid]) {
45+
hi = mid - 1;
3246
} else {
33-
right = mid - 1;
47+
lo = mid + 1;
3448
}
3549
}
3650

0 commit comments

Comments
(0)

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