找指定target的最左位置。
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) return -1;
if(nums.length == 0) return -1;
int left = 0; int right = nums.length -1; while(left + 1 < right){
int mid = (left + right) / 2;
if(nums[mid] < target){
left = mid;
}
else if(nums[mid] > target){
right = mid;
}
else if(nums[mid] == target){
right = mid;
}
}
if(nums[left] == target){
return left;
}
else if(nums[right] == target){
return right;
}
else return -1;
}
}