Given an array of sorted integers in ascending order, and a target integer, write a function to search target in nums array. If target exists, return the index of the target in the array, otherwise return -1.
Input: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Target: 5
Output: 4
Input: [-1,0,3,5,9,12]
Target: 24
Output: -1
1 <= nums.length <= 104
-104 < nums[i], target < 104
All the integers in nums are unique.
nums is sorted in ascending order.
Click to reveal
Try declaring two pointers, start
and end
and take advantage of the sorted nature of the array. Start will initialize from 0
and end will initialize from arr.length - 1
Click to reveal
Try calculating median
value of the array. Since the array is sorted, the target value will tell you if the it is present in the left part of the array or the right part.