Binary Search
You are given an array nums of distinct integers sorted in ascending order, and an integer target.
Return the index of target in nums, or -1 if it does not appear.
Your solution must run in O(log n) time, so checking the elements one by one is not the intended approach.
Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i], target <= 10^4- The values in
numsare distinct and sorted in ascending order.
Examples
Example 1
Input: nums = [-4,1,3,7,10,15], target = 7 Output: 3
7 sits at index 3.
Example 2
Input: nums = [-4,1,3,7,10,15], target = 2 Output: -1
2 would belong between 1 and 3, but it isn't in the array, so the answer is -1.
Example 3
Input: nums = [6], target = 6 Output: 0
With one element, the only possible index is 0.
JavaScript you'll use: Numbers, Math and integer tricks Arrays: create, read, update
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
function search(nums, target) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.