Find First and Last Position of Element in Sorted Array
Description
Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
Example 1:
Input: nums = [5,7,7,8,8,10]
, target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10]
, target = 6
Output: [-1,-1]
Solution(javascript)
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
let firstleft = 0, lastleft = 0;
let firstright = nums.length - 1, lastright = nums.length - 1;
let first = -1, last = -1;
let mid;
while (firstleft <= firstright) {
mid = Math.floor((firstleft + firstright) / 2);
if (nums[mid] === target && ( nums[mid-1] < nums[mid] || mid === 0)) {
first = mid;
break;
} else if (nums[mid] < target) {
firstleft = mid + 1;
} else {
firstright = mid - 1;
}
}
while (lastleft <= lastright) {
mid = Math.floor((lastleft + lastright) / 2);
if (nums[mid] === target && ( nums[mid+1] > nums[mid] || mid === nums.length-1)) {
last = mid;
break;
} else if (nums[mid] > target) {
lastright = mid - 1;
} else {
lastleft = mid + 1;
}
}
return [first, last];
};