题目描述:
给定一个有序数组nums,一个整数num,要求返回大于等于num的数字的最小下标
没有大于num的数返回-1;
对于有序排列查找指定值,可以选用二分查找
public class BinarySearch {
public static void main(String[] args) {
int[] nums =new int[]{1, 2, 3, 4, 5, 6, 8, 9, 41, 556};
int num =2;
System.out.println(binarySearch(num,nums));
}
private static int binarySearch(int num, int[] nums) {
int left =0;
int right = nums.length;
while (left < right){
int mid = left + (right - left) /2;
if(nums[mid] < num){
left = mid +1;
} else {
right = mid;
}
}
return left < nums.length ? left : -1;
}
}
网友评论