返回
手把手教你刷搜索技巧之二分答案法详解
前端
2023-10-15 07:05:09
掌握了二分答案法的基本思路之后,接下来手把手教你如何实现一个二分答案程序。
import java.util.Arrays;
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int target = 11;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("Target not found");
} else {
System.out.println("Target found at index " + result);
}
}
}
这个程序可以用来搜索一个有序数组中的目标值。如果目标值存在,则返回目标值在数组中的索引,否则返回 -1。
二分答案法是一种非常高效的搜索算法,时间复杂度为 O(log n)。因此,它非常适合用于搜索大型数据集。
二分答案法的优缺点
二分答案法是一种非常高效的搜索算法,具有以下优点:
- 时间复杂度为 O(log n),非常适合用于搜索大型数据集。
- 实现简单,易于理解和使用。
- 可以用于搜索各种类型的数据,包括数字、字符串和对象。
二分答案法也有一些缺点,包括:
- 只能用于搜索有序数组。
- 如果数据量非常大,二分答案法可能会导致栈溢出。
- 二分答案法无法用于搜索无序数据。
二分答案法的应用
二分答案法有许多应用,包括:
- 在数组中搜索目标值。
- 在字符串中搜索子串。
- 在集合中搜索元素。
- 在图形中搜索路径。
- 在游戏中搜索最优解。
二分答案法是一种非常强大的搜索算法,可以用于解决许多问题。如果你需要搜索大量的数据,二分答案法是一个非常好的选择。