二分搜索的题目
程序员文章站
2022-06-17 19:18:17
...
##二分搜索
针对有序的数组,主要是一些边界的问题
##leetcode_35
##题解
public class Leetcode_35 {
public int searchInsert(int[] nums, int target) {
int l = 0;
int r = nums.length-1;
while(l<=r)
{
int mid = (r+l)/2;
if(target==nums[mid])
return mid;
else if(target>nums[mid])
l = mid+1;
else
r = mid-1;
}
return l;
}
public static void main(String[] args)
{
int[] nums ={1,3,5,6};
Leetcode_35 test = new Leetcode_35();
int a = test.searchInsert(nums,7);
System.out.println(a);
}
}
##剑指offer_11
import java.util.ArrayList;
public class Solution {
public int minNumberInRotateArray(int [] array) {
int l = 0;
int r = array.length-1;
while(l<r)
{
int m = (l+r)/2;
if(array[m]<=array[r])
r = m;
else
l = m+1;
}
return array[l];
}
}
上一篇: 二分总结
下一篇: 数据结构——树与二叉树