·  阅读 647

# leetcode刷题-二分查找&分治

## 1、在一个重复元素的数组中查找key的最左位置

``````var binarySearch(nums, key) {
let left = 0, right = nums.length - 1;

while(left < right) {
let mid = Math.floor(left + (right - left) / 2);
if (nums[mid] >= key) {
right = mid;
} else {
left = mid + 1;
}
}

return left;
}

## 2、x 的平方根

``````var mySqrt = function(x) {
if (x <= 1) return x;

let left = 1, right = x;

while(left <= right) {
const mid = Math.floor(left + (right - left) / 2);
const value = mid ** 2;

if (value === x) {
return mid;
} else if (value > x) {
right = mid - 1;
} else {
left = mid + 1;
}
}

return right;
};

## 3、寻找比目标字母大的最小字母

``````var nextGreatestLetter = function(letters, target) {
const n = letters.length;
if (target >= letters[n - 1]) {
return letters[0];
}

let left = 0, right = n - 1;

while(left <= right) {
const mid = Math.floor(left + (right - left) / 2);
if (letters[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}

return letters[left];
};

## 4、第一个错误的版本

``````var solution = function(isBadVersion) {
/**
* @param {integer} n Total versions
* @return {integer} The first bad version
*/
return function(n) {
let left = 0, right = n;

while(left <= right) {
const mid = Math.floor(left + (right - left) / 2);
right = mid - 1;
} else {
left = mid + 1;
}
}

return left;
};
};

## 5、寻找旋转排序数组中的最小值

``````var findMin = function(nums) {
let left = 0, right = nums.length - 1;

while (left < right) {
const mid = Math.floor(left + (right - left) / 2);
if (nums[mid] > nums[right]) {
left = mid + 1;
} else {
right = mid;
}
}

return nums[left];
};

## 6、 在排序数组中查找元素的第一个和最后一个位置

``````var searchRange = function(nums, target) {
const left = findLeft(nums, target);
const right = findLeft(nums, target + 1) - 1;
if (left < nums.length && nums[left] === target) {
return [left, right];
}
return [-1, -1];
};

function findLeft(nums, target) {
const n = nums.length;
if (target > nums[n - 1]) return n;

let left = 0, right = nums.length - 1;

while(left < right) {
const mid = Math.floor(left + (right - left) / 2);
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}

return right;
}

## 7、为运算表达式设计优先级

``````var diffWaysToCompute = function(expression) {
const n = expression.length;
const res = [];
const value = Number(expression);
if (!isNaN(value)) return [value];

for (let i = 0; i < n; i++) {
const char = expression[i];
let leftArr = [], rightArr = [];
if (char === '+' || char === '-' || char === '*') {
leftArr = diffWaysToCompute(expression.substring(0, i));
rightArr = diffWaysToCompute(expression.substring(i + 1, n));
}

for (let x of leftArr) {
for (let y of rightArr) {
switch(char) {
case '+':
res.push(x + y);
break;
case '-':
res.push(x - y);
break;
case '*':
res.push(x * y);
break;
}
}
}
}

return res;
};