Find First and Last Position of Element in Sorted Array
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function (nums, target) {
const firstOcurance = searchFirstOccurance(nums, target);
const lastOcurrance = searchLastOccurance(nums, target);
if (firstOcurance === -1) {
return [-1, -1];
} else {
return [firstOcurance, lastOcurrance];
}
};
var searchFirstOccurance = function (nums, target) {
let high = nums.length - 1;
let low = 0;
while (low <= high) {
let mid = parseInt((low + high) / 2);
if (nums[mid] > target) {
high = mid - 1;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
if (mid === 0 || nums[mid - 1] !== nums[mid]) {
return mid;
} else {
high = mid - 1;
}
}
}
return -1;
};
var searchLastOccurance = function (nums, target) {
let high = nums.length - 1;
let low = 0;
while (low <= high) {
let mid = parseInt((low + high) / 2);
if (nums[mid] > target) {
high = mid - 1;
} else if (nums[mid] < target) {
low = mid + 1;
} else {
if (mid === nums.length - 1 || nums[mid] !== nums[mid + 1]) {
return mid;
} else {
low = mid + 1;
}
}
}
return -1;
};
console.log(searchRange([5, 7, 7, 8, 8, 10], 8));
Top comments (2)
indexOf and lastIndexOf ??
Yes, but this question is of type Binary Search algo... & it gives condition of not using the defined methods..
leetcode.com/problems/find-first-a...