普通二分查找代码
循环
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);
}
}
通过枚举长度
static boolean flag(int i,int[] arr,int target) {
int sum = 0;
for (int j = 0; j <= i; j++) {
sum += arr[j];
if (sum >= target) {
return true;
}
}
return false;
}
static void shortestSubsequenceAnd2(int[] arr,int target) {
int min = Integer.MAX_VALUE;
for (int i = 1; i < arr.length; i++) {
if (flag(i,arr,target)) {
min = Math.min(min,i);
}
}
if (min == Integer.MAX_VALUE) {
System.out.println("不存在");
} else {
System.out.println(min);
}
}
变形5
给定一个数 num,求解第一个大于x的平方数
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 > x) {
right = mid-1;
} else {
left = mid+1;
}
}
return left*left;
}
}
|