Description
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.
Challenge
If the count of numbers is bigger than 2^32, can your code work properly?
4/26/2017
算法班
不是很明白challenge说数字大于2^32的意思,二分法是合理的吗?
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 //write your code here 9 if (nums == null || nums.length == 0) return -1; 10 if (target > nums[nums.length - 1] || target < nums[0]) return -1; 11 12 int start = 0, end = nums.length - 1; 13 while (start + 1 < end) { 14 int mid = start + (end - start) / 2; 15 if (nums[mid] >= target) { 16 end = mid; 17 } else { 18 start = mid; // to find the first position, we need to include target in the search range 19 } 20 } 21 22 if (nums[start] == target) return start; 23 else if (nums[end] == target) return end; 24 return -1; 25 } 26 }