二分查找及其变形
Posted echie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找及其变形相关的知识,希望对你有一定的参考价值。
[LeetCode] 35 Search Insert Position
题目
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
测试案例
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
代码如下
class Solution {
public int searchInsert(int[] nums, int target) {
int start = 0, end = nums.length - 1, mid;
while(start <= end){
mid = (start + end) >> 1;
if(nums[mid] == target){
return mid;
}
else if(nums[mid] > target){
end = mid - 1;
}
else{
start = mid + 1;
}
}
return start;
}
}
[LeetCode 34] Find First and Last Position of Element in Sorted Array
题目
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm‘s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
测试案例
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
代码如下
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[2];
if(nums.length == 0){
res[0] = res[1] = -1;
return res;
}
res[0] = find(nums, target, true);
res[1] = find(nums, target, false);
if(res[0] >= nums.length || nums[res[0]] != target){
res[0] = -1;
res[1] = -1;
}
return res;
}
int find(int[] nums, int target, boolean left){
int mid;
int start = 0, end = nums.length - 1;
while(start <= end){
mid = (start + end) >> 1;
if(nums[mid] > target){
end = mid - 1;
}
else if(nums[mid] == target){
if(left){
end = mid - 1;
}
else{
start = mid + 1;
}
}
else{
start = mid + 1;
}
}
return left ? start : end;
}
}
[LeetCode 153] Find Minimum in Rotated Sorted Array
题目
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
测试案例
Input: [3,4,5,1,2]
Output: 1
Input: [4,5,6,7,0,1,2]
Output: 0
代码如下
class Solution {
public int findMin(int[] nums) {
int n = nums.length, start = 0, end = n - 1, mid;
while(start < end){
if(nums[start] < nums[end]){
return nums[start];
}
mid = (start + end) >> 1;
if(nums[mid] >= nums[start]){
start = mid + 1;
}
else{
end = mid;
}
}
return nums[start];
}
}
以上是关于二分查找及其变形的主要内容,如果未能解决你的问题,请参考以下文章