一:用法
1、有序、无重复的数组
2、当有重复时,可以先用二分法查找到,然后使用左右滑动来找到边界
3、二分法例子:
- 给定一个n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1。
public class Search {
public static void main(String[] args) {
int[] nums = {-1, 0, 3, 5, 9, 12};
// int target = 9;
int target = 2;
//方法一:暴力循环
int i = method1(nums, target);
System.out.println(i);
//方法二:target【】双闭区间
int get2 = method2(nums, target);
System.out.println(get2);
//方法三:【)左闭右开区间
int get3 = method3(nums, target);
System.out.println(get3);
}
private static int method3(int[] nums, int target) {
int left = 0;
int right = nums.length;//[)
while (left < right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] > target) {
right = mid;
} else if (nums[mid] < target) {
left =mid+1;
} else if (nums[mid] == target) {
return mid;
}
}
return -1;
}
private static int method2(int[] nums, int target) {
int left = 0;
int right = nums.length - 1; //因为此处是-1,所以要用双闭区间
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] == target) {
return mid;
}
}
//未找到目标
return -1;
}
private static int method1(int[] nums, int target) {
int get = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target) {
get = i;
break;
}
}
return get;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。