力扣 - 二分法
算法题目
二分查找算法(Binary Search)
- 解决问题:在有序数组中查找是否存在给定元素,存在则返回相应数组下标
- 思想:通过对半查找缩小搜索范围,降低时间复杂度
将给定目标元素与数组中间元素进行对比,判断下一次搜索数组范围
二分查找算法
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示:
- 你可以假设 nums 中的所有元素是不重复的。
- n 将在 [1, 10000]之间。
- nums 的每个元素都将在 [-9999, 9999]之间。
class Solution {
public int search(int[] nums, int target) {
int lowIndex = 0;
int highIndex = nums.length - 1;
int midIndex = highIndex/2;
while(lowIndex<=highIndex){
if (target == nums[midIndex]){
return midIndex;
}
if (target > nums[midIndex]){
lowIndex = midIndex + 1;
}else {
highIndex = midIndex - 1;
}
midIndex = (highIndex + lowIndex)/2;
}
return -1;
}
}
你是产品经理,目前正在带领一个团队开发新的产品。不幸的是,你的产品的最新版本没有通过质量检测。由于每个版本都是基于之前的版本开发的,所以错误的版本之后的所有版本都是错的。
假设你有 n 个版本 [1, 2, ..., n],你想找出导致之后所有版本出错的第一个错误的版本。
你可以通过调用 bool isBadVersion(version) 接口来判断版本号 version 是否在单元测试中出错。实现一个函数来查找第一个错误的版本。你应该尽量减少对调用 API 的次数。
输入:n = 5, bad = 4
输出:4
解释:
调用 isBadVersion(3) -> false
调用 isBadVersion(5) -> true
调用 isBadVersion(4) -> true
所以,4 是第一个错误的版本。
输入:n = 1, bad = 1
输出:1
提示:
1 <= bad <= n <= $2^{31} - 1$
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int lowVer = 1;
int highVer = n;
int midVersion = 1 + (n - 1)/2;
while(lowVer<highVer){
if(isBadVersion(midVersion)){
highVer = midVersion;
}else {
lowVer = midVersion + 1;
}
midVersion = lowVer + (highVer - lowVer)/2;
}
return lowVer;
}
}
3.搜索有序数组并插入
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。请必须使用时间复杂度为 O(log n) 的算法。
输入: nums = [1,3,5,6], target = 5
输出: 2
输入: nums = [1,3,5,6], target = 2
输出: 1
class Solution {
public int searchInsert(int[] nums, int target) {
Integer lowIndex = 0;
Integer highIndex = nums.length - 1;
Integer midIndex = lowIndex + (highIndex - lowIndex)/2;
while(lowIndex<=highIndex){
if (target == nums[midIndex]){
return midIndex;
}
if (target > nums[midIndex]){
lowIndex = midIndex + 1;
}else {
highIndex = midIndex - 1;
}
midIndex = lowIndex + (highIndex - lowIndex)/2;
}
return lowIndex;
}
}

浙公网安备 33010602011771号