We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 简单
Related Topics: 数组, 二分查找
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
n
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, 10000]
[-9999, 9999]
Language: JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ // 二分查找 var search = function(nums, target) { let left = 0, right = nums.length - 1 while (left <= right) { const mid = Math.floor((right - left) / 2) + left const num = nums[mid] if (num === target) { return mid } else if (num > target) { right = mid - 1 } else { left = mid + 1 } } return -1 };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
704. 二分查找
Description
Difficulty: 简单
Related Topics: 数组, 二分查找
给定一个
n
个元素有序的(升序)整型数组nums
和一个目标值target
,写一个函数搜索nums
中的target
,如果目标值存在返回下标,否则返回-1
。示例 1:
示例 2:
提示:
nums
中的所有元素是不重复的。n
将在[1, 10000]
之间。nums
的每个元素都将在[-9999, 9999]
之间。Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: