一.二分的概念
二分算法 是用来在一个有序数组中查找某一元素的算法,时间复杂度为O(log n)。
二分法:不断地把有序数组的区间一分为二,使区间的两个端点逐步逼近,进而得到近似值的方法。
二.二分的两种模版
1.查找当前有序数组中 >=x 的第一个数:
int l=0,r=arr.length-1;
int x=scan.nextInt();
while(1<r)
{
int mid=(1+r)/2;//取区间中间位置靠左的值
if(arr[mid]>=x)
r=mid;//区间向左缩短一半
else
l=mid+1;//区间向右缩短一半
}
2.查找当前有序数组中 <=x 的最后一个数
int l=0,r=arr.length-1;
int x=scan.nextInt();
while (l<r)
{
int mid=(1+r+1)/2;//取区间中间位置靠右的值
if(arr[mid]>x)
r=mid-1;//区间向左缩短一半
else
l=mid;//区间向右缩短一半
}
三.例题
1.二分查找数组元素
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int x=scan.nextInt();
int []data=new int [200];
for(int i = 0 ; i < 200 ; i ++)
data[i]=4*i+6;
int l=0,r=data.length-1;
int mid;
while(l<r)
{
mid=(l+r)/2;
if(x<=data[mid])
{
r=mid;
}
else if(x>data[mid])
{
l=mid+1;
}
}
System.out.println(l);
scan.close();
}
2.全都有的子序列
static boolean check(int mid,int []a,int m)//滑动窗口
{
int n=a.length;
int []f=new int[1001];
//a[i]的取值范围是1~1000;这个数组的作用是记录数组的出现次数
int l=0,r=0,ans=0;
while(r<n)//当右指针未到数组末尾时
{
f[a[r]]++;
if(f[a[r]]==1)
ans++;
if(r-l+1>mid)//表示超出区间范围
{
f[a[l]]--;
if(f[a[l]]==0)
ans--;
l++;
}
r++;
if(ans>=m)
return true;
}
return false;
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n=scan.nextInt();
int []a=new int[n];
HashSet<Integer> set=new HashSet<Integer>();
for(int i=0;i<n;i++)
{
a[i]=scan.nextInt();
set.add(a[i]);
}
int m=set.size();
int l=1,r=n,mid;
while(l<r)
{
mid=(l+r)/2;
if(check(mid,a,m))
r=mid;
else
l=mid+1;
}
System.out.println(l);
scan.close();
}