二分查找有序数组中的特定值
1、题目背景
给定一个n个元素有序的(升序)整型数组nums和一个目标值target写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1
2、代码实现
public class Solution {
public static void main(String[] args) {
int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(search(nums, 1));
}
/**
* 给定一个n个元素有序的(升序)整型数组nums和一个目标值target
* 写一个函数搜索nums中的target,如果目标值存在返回下标,否则返回-1
* @param nums
* @param target
* @return
*/
public static int search(int[] nums, int target) {
if (target < nums[0] || target > nums[nums.length - 1]) {
return -1;
}
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + ((right - left) >> 1);
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1;
else if (nums[mid] > target)
right = mid - 1;
}
return -1;
}
}
3、结果展示
6
Process finished with exit code 0