For a given sorted array (ascending order) and a number target
, find the first index of this number in time O(log n)
complexit Y.
If the target number does not exist in the array, return -1
.
Example
If the array is [1, 2, 3, 3, 4, 5, 10]
, for given target 3
, return 2
.
Analysis:
Obviously with binary search, but because we need to find the first one, we have to judge.
1 classSolution {2 /**3 * @param nums:the integer array.4 * @param target:target to find.5 * @return: The first position of target. Position starts from 0.6 */7 Public intBinarySearch (int[] Nums,inttarget) {8 if(Nums = =NULL|| Nums.length = =0)return-1;9 Ten intStart =0; One intEnd = Nums.length-1; A - while(Start <=end) { - intMID = start + (End-start)/2; the if(Nums[mid] = =target) { - if(Mid! =0&& Nums[mid-1] ==target) { -End = Mid-1; -}Else { + returnmid; - } +}Else if(Nums[mid] <target) { AStart = mid +1; at}Else { -End = Mid-1; - } - } - return-1; - } in}
Reference Please specify Source: cnblogs.com/beiyeqingteng/
First Position of Target