蓝桥杯刷题笔记:二分查找
Posted 爱敲代码的三毛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了蓝桥杯刷题笔记:二分查找相关的知识,希望对你有一定的参考价值。
普通二分查找代码
循环
static int find(int[] arr,int target)
int left = 0;
int right = arr.length-1;
int mid = 0;
while (left <= right)
mid = (right-left)/2 + left;
if (arr[mid] > target)
right = mid-1;
else if (arr[mid] < target)
left = mid+1;
else
return mid;
return -1;
递归
static int find2(int[] arr,int left,int right,int target)
if (left > right)
return -1;
int mid = (right-left)/2 + left;
if (arr[mid] > target)
return find2(arr,left,mid-1,target);
else if (arr[mid] < target)
return find2(arr,mid+1,right,target);
else if (arr[mid] == target)
return mid;
return -1;
二分查找变形
变形1
给定有序序列,找到序列中大于或者等于 target最小的那个的数字
static int find3(int[] arr,int target)
int left = 0;
int right = arr.length-1;
int mid = 0;
while (left <= right)
mid = (right-left)/2 + left;
if (arr[mid] >= target)
right = mid-1;
else
left = mid+1;
if (left >= arr.length)
return -1;
return arr[left];
变形2
给定有序序列,找到序列中大于 target最小的那个的数字
static int find4(int[] arr,int target)
int left = 0;
int right = arr.length-1;
int mid = 0;
while (left <= right)
mid = (right-left)/2 + left;
if (arr[mid] > target)
right = mid-1;
else
left = mid+1;
if (left >= arr.length)
return -1;
return arr[left];
变形3
给定有序序列,找到序列中小于 target最大的那个的数字
static int find5(int[] arr,int target)
int left = 0;
int right = arr.length-1;
int mid = 0;
while (left <= right)
mid = (right-left)/2 + left;
if (arr[mid] <= target)
left = mid+1;
else
right = mid-1;
if (right < 0)
return -1;
return arr[right];
变形4
给定一个 整数序列,让你取一个字段,使得区间和大于等于x,问这个字段最短可能长度是多少
示例:
[1,2,4,7,9] ,给定 target = 13 时应该得到 2, target = 3 时应该得到1,target 大于 23时应该不存在
暴力代码
static void shortestSubsequenceAnd(int[] arr,int target)
int min = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++)
int sum = 0;
for (int j = i; j < arr.length; j++)
sum += arr[j];
if (sum >= target)
min = Math.min(min,j-i+1);
break;
System.out.println("i: "+i +" j:"+j);
if (min == Integer.MAX_VALUE)
System.out.println("不存在");
else
System.out.println(min);
变形5
给定一个数 num,求解第一个大于x的平方数
/**
* 求第一个大于x的平方数
* @return
*/
static int isPerfectSquare(int x)
int n = x;
while (true)
n++;
int left = 1;
int right = n;
int mid = 0;
while (left <= right)
mid = (right-left)/2 + left;
if (mid*mid < n)
left = mid+1;
else if (mid*mid > n)
right = mid-1;
else
return n;
以上是关于蓝桥杯刷题笔记:二分查找的主要内容,如果未能解决你的问题,请参考以下文章