给定一个排序的整数数组(升序)和一个要查找的整数target
,用O(logn)
的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1
。
public class Solution { /** * @param nums: The integer array. * @param target: Target to find. * @return: The first position of target. Position starts from 0. */ public int binarySearch(int[] nums, int target) { // write your code here int low = 0; int high = nums.length-1; return find(nums, low, high, target); } public int find(int[] num, int low, int high, int target) { if (low == high && target == num[low]) { return low; } int middle = (low + high)/2; if (target >= num[low] && target <= num[middle]) { return find(num, low, middle, target); } if (target > num[middle] && target <= num[high]) { return find(num, middle+1, high, target); } return -1; } }