Problem:
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?
Steps:
1. initialize start position, end position;
2. loop start
find mid value;
if mid value >= target, move end to the middle pint
if mid < target, move start to the middle point
end loop
3. check start point and end point
if start point is the target, return start current position
if end point is the target, return end current position
else return -1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public int binarySearch(int[] nums, int target) { int start = 0; int end = nums.length - 1; if(nums[start] > target || nums[end] < start) return -1; while(start + 1 < end) { int mid = start + (end - start)/2; // make sure no integer overflow if(nums[mid] == target) { end = mid; } else if(nums[mid] > target) { end = mid; } else { start = mid; } } if(nums[start] == target) { return start; } if(nums[end] == target) { return end; } return -1; } |