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
.
Have you met this question in a real interview?
Yes
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?
1 public int binarySearch(int[] nums, int target) 2 { 3 //write your code here 4 if(nums.length==0)return -1; 5 int left = 0; 6 int right = nums.length-1; 7 while(left+1 <right) 8 { 9 int mid = (left + right) /2; 10 if(target==nums[mid]) 11 { 12 right = mid; 13 } 14 15 if(target<nums[mid]) 16 { 17 right = mid-1; 18 } 19 if(target>nums[mid]) 20 { 21 left = mid+1; 22 } 23 24 } 25 26 if(nums[left]==target) return left; 27 if(nums[right]==target) return right; 28 return -1; 29 }