题目
704. 二分查找
题解
代码
public class code704 {
public static int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int nums[] = { -1, 0, 3, 5, 9, 12 };
int target1 = 9;
int target2 = 2;
int index1 = search(nums, target1);
int index2 = search(nums, target2);
System.out.println(index1);
System.out.println(index2);
}
}
参考
- 二分查找细节详解——题解一
- 画解算法:704. 二分查找——题解二