题解里的二分查找都是比较mid和target之后,left+1或right-1,这样查找的效率感觉不高啊,如果直接将left = mid或right = mid,就直接切一半来找,感觉要快一点。
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
function search( nums , target ) {
// write code here
let left = 0, right = nums.length-1;
let mid = Math.floor((left + right)/2);
if (nums.length == 0 || (nums.length == 1 && nums[0] != target)) {
return -1;
} else if (nums.length == 1 && nums[0] == target) {
return 0;
}
while (right - left >= 1) {
if (right - left == 1 && nums[right] == target) {
return right;
}
if (target == nums[mid]) {
return mid
} else if (target > nums[mid]) {
if (right - left == 1 && nums[right] != target) {
return -1;
}
left = mid
} else {
right = mid;
}
mid = Math.floor((left + right)/2);
}
return -1
}
module.exports = {
search : search
};