# 算法刷题——二分法

·  阅读 1518

## 704 二分查找

``````示例 1:

### 解题思路

``````/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let right = nums.length - 1;
let left = 0;
while(left <= right){
let mid = Math.floor((right + left) / 2);
if(nums[mid] === target)
return mid;
if(nums[mid] > target){
right = mid - 1;
}else{
left = mid + 1 ;
}
}
return -1;
};

## 69 x的平方根

``````示例 1:

### 解题思路

``````/**
* @param {number} x
* @return {number}
*/
var mySqrt = function(x) {
if(x === 0)
return 0;
if(x === 1)
return 1;
let left = 0;
let right = x;
let res = -1;
while(left <= right){
let mid = Math.floor((left + right) / 2);
//let mid = (left + right) >> 1; 也可以用移位
let sum = mid * mid;
if(sum === x)
return mid;
if(sum > x){
right = mid - 1;
}else{
res = mid;
left = mid + 1;
}
}
return res;

};

## 50Pow(x, n)

``````示例 1：

### 解题思路1

``````/**
* @param {number} x
* @param {number} n
* @return {number}
*/
let myPow = function(x, n) {
if(x === 0)
return 0;
if(n === 0)
return 1;
let sum = 1;
let mi = n > 0 ? n : -n;
while(mi--){
sum *= x;
}
if(n > 0){
return sum;
}else{
return 1 / sum;
}
};

### 解题思路2

``````/**
* @param {number} x
* @param {number} n
* @return {number}
*/
let myPow = function(x, n)  {
if(n === 0)
return 1;
if(n === 1)
return x;
let abs = Math.abs(n);
let isMinus = n !== abs;
let sum = abs % 2 ? x * myPow(x,abs-1): myPow(x*x, abs/2);
return isMinus ? 1 / sum : sum;

};