javascript - Find First and Last Position of Element in Sorted Array
问题描述
I am trying to solve the LeetCode problem Find First and Last Position of Element in Sorted Array:
Given an array of integers
nums
sorted in ascending order, find the starting and ending position of a giventarget
value.If
target
is not found in the array, return[-1, -1]
.You must write an algorithm with
O(log n)
runtime complexity.
I am writing this code:
var searchRange = function(nums, target) {
nums = nums.sort((a, b) => (a-b))
let result = [];
for(let i = 0; i < nums.length; i++) {
if (nums[i] == target) {
result.push(i)
} else {
result = [-1, -1]
}
}
return result
};
console.log(searchRange([5,7,7,8,8,10], 8));
It should return:
[3, 4]
but it returns:
[-1, -1]
What is wrong?
解决方案
Your else
code is wiping out results from the previous iteration of the loop.
However, your code is not efficient:
First, it calls sort
on an array that is given to be already sorted: so leave that out.
Secondly, as your code is visiting every element in the array, you still get a time complexity of O(n), not O(logn).
To get O(logn) you should implement a binary search, and then perform a search to find the start of the range, and another to find the end of it.
Here is how that could work:
function binarySearch(nums, target) {
let low = 0;
let high = nums.length;
while (low < high) {
let mid = (low + high) >> 1; // half way
if (nums[mid] > target) {
high = mid;
} else {
low = mid + 1;
}
}
return high; // first index AFTER target
}
function searchRange(nums, target) {
let end = binarySearch(nums, target);
let start = binarySearch(nums, target - 1);
return start === end ? [-1, -1] : [start, end - 1];
}
console.log(searchRange([5,7,7,8,8,10], 8));
推荐阅读
- jestjs - 在测试中加载模块时,如何使用 Jest 测试将 pino 调试日志写入标准输出?
- swiftui - SwiftUI tapGesture 是不是超级贪心?
- android - 如何在音频过程中使用超强时间拉伸课程
- c++ - 如何在多线程中正确使用 unique_ptr 进行多态性?
- jmeter - JMeter Listener - 仅在发生错误时创建错误文件
- javascript - 如何解决无法在Jquery Datatable中设置未定义的属性'_DT_CellIndex'
- android-studio - 在 Flutter 中显示 ListView 的内容并显示从画廊上传的图像
- c - C 编程二维数组。为什么这个程序中的 int j 总是默认为零,即使它是一个自动变量?
- javascript - Jquery 每个循环不显示 JSON 项目的属性
- regex - 正则表达式捕获两个数字之间的第一个字符串