题目链接:https://leetcode-cn.com/problems/binary-search/
就是一道经典的二分查找题目,可以使用递归,也可以使用非递归
递归解析:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let left = 0;
let right = nums.length-1;
return midSearch(nums,left,right,target);
};
function midSearch(nums,left,right,target){
if(left > right) return -1;
let mid = ((right - left) > 2) + left;
if(target === nums[mid]){
return mid;
}else if(target < nums[mid]){
return midSearch(nums,left,mid-1,target);
}else{
return midSearch(nums,mid+1,right,target);
}
}
非递归解析:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let left = 0;
let right = nums.length-1;
while(left <= right){
let mid = ((right -left)>2) + left;
if(target === nums[mid]){
return mid;
}else if(target > nums[mid]){
left = mid+1;
} else{
right = mid-1;
}
}
return -1;
};