题目:给定一个有序数组nums,和一个目标值target,求这个target在数组nums中的下标,不存在则返回-1。
【Java版】代码实现
public class MyTest {
public static void main(String[] args) {
int[] array = new int[]{1, 2, 3, 4, 5, 6, 7};
System.out.println(binarySearch(array, 1)); // 测试边界
System.out.println(binarySearch(array, 7)); // 测试边界
System.out.println(binarySearch(array, 8)); // 测试边界
System.out.println(binarySearch(array, 2)); // 测试边界
}
public static int binarySearch(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
int mid;
while (left <= right) {
mid = (left + right) / 2; // 数组很大,left+right超过int最大值?
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
}
注意:
- while循环条件:left<=right
- 如果nums[mid] == target,则直接将mid返回