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
.
If the array is [1, 2, 3, 3, 4, 5, 10]
, for given target 3
, return 2
.
分析:
很明显的用binary search, 但是因为要找第一个,所以,我们需要判断一下。
1 class Solution { 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 int binarySearch(int[] nums, int target) { 8 if (nums == null || nums.length == 0) return -1; 9 10 int start = 0; 11 int end = nums.length - 1; 12 13 while (start <= end) { 14 int mid = start + (end - start) / 2; 15 if (nums[mid] == target) { 16 if (mid != 0 && nums[mid - 1] == target) { 17 end = mid - 1; 18 } else { 19 return mid; 20 } 21 } else if (nums[mid] < target) { 22 start = mid + 1; 23 } else { 24 end = mid - 1; 25 } 26 } 27 return -1; 28 } 29 }
参考请注明出处: cnblogs.com/beiyeqingteng/
原文:http://www.cnblogs.com/beiyeqingteng/p/5639277.html