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
and target value
[5, 7, 7, 8, 8, 10]
8
,
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) / );
if (nums[pos] === target) {
if (result[] === - && result[] === -) {
result[] = result[] = pos;
} else {
result[] = pos < result[] ? pos : result[];
result[] = pos > result[] ? pos : result[];
}
search(left, pos - , result, nums, target);
search(pos + , right, result, nums, target);
} else if (nums[pos] > target) {
search(left, pos - , result, nums, target);
} else {
search(pos + , right, result, nums, target);
}
};
var searchRange = function(nums, target) {
var result = [-, -];
search(, nums.length - , result, nums, target);
return result;
};