leetcode 第34题”Search for a range”描述如下:
Given a sorted array of integers, 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]
.
For example,
Given[5, 7, 7, 8, 8, 10]
and target value8
,
return[3, 4]
.
这首先条件是给了我们一个从小到大已经排列好的数组,然后找到数组中值等于value的起始键和终止键,由于题目说复杂度控制在O(logn)其实就已经变相暗示用二分法解决了,最传统的方法当然是双指针,但是自己想练练自己递归解题的思路,就用递归解的:
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var search = function(left, right, result, nums, target) {
if (left > right) {
return;
}
var pos = Math.floor((right + left) / 2);
if (nums[pos] === target) {
if (result[0] === -1 && result[1] === -1) {
result[0] = result[1] = pos;
} else {
result[0] = pos < result[0] ? pos : result[0];
result[1] = pos > result[1] ? pos : result[1];
}
search(left, pos - 1, result, nums, target);
search(pos + 1, right, result, nums, target);
} else if (nums[pos] > target) {
search(left, pos - 1, result, nums, target);
} else {
search(pos + 1, right, result, nums, target);
}
};
var searchRange = function(nums, target) {
var result = [-1, -1];
search(0, nums.length - 1, result, nums, target);
return result;
};