二分查找
Easy
array
binary-search
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示:
- 1 <= nums.length <= 10^4
- -10^4 < nums[i], target < 10^4
- nums 中的所有整数 互不相同
- nums 按升序排列
Sample Test Cases
Example 1
Input:
[-1,0,3,5,9,12] 9
Expected Output:
4
Example 2
Input:
[-1,0,3,5,9,12] 2
Expected Output:
-1
Keyboard shortcuts:
- • Ctrl/Cmd + Enter to submit
📈 Statistics
Submissions
2
Accepted
0
Acceptance Rate
0.0%