First Position of Target

时间:2022-10-03 05:09:51

For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity.

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.

分析:
很明显的用binary search, 但是因为要找第一个,所以,我们需要判断一下。

 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) {
if (nums == null || nums.length == ) return -; int start = ;
int end = nums.length - ; while (start <= end) {
int mid = start + (end - start) / ;
if (nums[mid] == target) {
if (mid != && nums[mid - ] == target) {
end = mid - ;
} else {
return mid;
}
} else if (nums[mid] < target) {
start = mid + ;
} else {
end = mid - ;
}
}
return -;
}
}

参考请注明出处: cnblogs.com/beiyeqingteng/