定义
输入:一个有序的元素列表
输出:if(包含) { return 查找元素的位置 } else { return null }
复杂度:O()
leetcode
- 对应题:704. 二分查找
- 解题:
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
if (nums.length === 0 || nums[nums.length - 1] < target || nums[0] > target) {
return -1
}
if (nums[0] === target) {
return 0
}
if (nums[nums.length - 1] === target) {
return nums.length - 1
}
var low = parseInt(nums.length / 2)
var high = nums.length - 1
while(low <= high - 1) {
if(nums[low] === target) {
return low
} else {
if (low === high -1) {
return -1
}
if(nums[low] > target) {
high = low
low = parseInt(low / 2)
} else {
low = low + parseInt((high - low) / 2)
}
}
}
return -1
};