开始刷题
- 69. Sqrt(x) (Easy)
- 744. Find Smallest Letter Greater Than Target (Easy)
- 540. Single Element in a Sorted Array (Medium)
- 278. First Bad Version (Easy)
- 153. Find Minimum in Rotated Sorted Array (Medium)
- 34. Find First and Last Position of Element in Sorted Array
69. x 的平方根
var mySqrt = function (x) {
let left = 0;
let right = x;
while (left <= right) {
let mid = Math.floor(left + (right - left) / 2);
let sqrt = Math.floor(x / mid);
if (mid === sqrt) {
return mid;
} else if (mid > sqrt) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return right;
};
744. 寻找比目标字母大的最小字母
var nextGreatestLetter = function (letters, target) {
let left = 0;
let right = letters.length - 1;
while (left <= right) {
const mid = Math.floor(left + (right - left) / 2);
if (letters[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left >= letters.length ? letters[0] : letters[left];
};
540. 有序数组中的单一元素
tips:通过判断 mid 是与左边相等还是和右边相等,然后根据 mid 的奇偶情况分类。
var singleNonDuplicate = function (nums) {
let left = 0, right = nums.length - 1;
while (left < right) {
const mid = Math.floor(left + (right - left) / 2);
const isEven = mid % 2 === 1;
if (nums[mid] === nums[mid - 1]) {
if(isEven)left = mid + 1;
else right = mid - 2;
} else if (nums[mid] === nums[mid + 1]) {
if(isEven) right = mid - 1;
else left = mid + 2;
} else {
return nums[mid];
}
}
return nums[left];
};
278. 第一个错误的版本
var solution = function (isBadVersion) {
/**
* @param {integer} n Total versions
* @return {integer} The first bad version
*/
return function (n) {
let left = 1;
let right = n;
while (left < right) {
const mid = Math.floor(left + (right - left) / 2);
if (isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
};
return left;
};
}
153. 寻找旋转排序数组中的最小值
tips:和最后一个值比
var findMin = function (nums) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const mid = Math.floor(left + (right - left) / 2);
if (nums[mid] > nums[nums.length - 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left]
};
34. 在排序数组中查找元素的第一个和最后一个位置
tips:两次二分查找,第一次找元素的第一个,第二次找最后一个(也就是下一个元素的第一个的索引减一)
var searchRange = function (nums, target) {
let ans = [-1, -1];
let leftIndex = binarySearch(nums, target);
let rightIndex = binarySearch(nums, target + 1) - 1;
if (leftIndex < nums.length && nums[leftIndex] == target) {
return ans = [leftIndex, Math.max(leftIndex,rightIndex)];
}
return ans;
};
function binarySearch(nums, target) {
let left = 0, right = nums.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}