Skip to content
New issue

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

704. 二分查找 #69

Open
buuing opened this issue May 18, 2022 · 0 comments
Open

704. 二分查找 #69

buuing opened this issue May 18, 2022 · 0 comments

Comments

@buuing
Copy link
Owner

buuing commented May 18, 2022

给定一个 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

提示:

  • 你可以假设 nums 中的所有元素是不重复的。
  • n 将在 [1, 10000]之间。
  • nums 的每个元素都将在 [-9999, 9999]之间。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




  • 二分法查找
const search = (nums, target) => {
  const len = nums.length
  const fn = (start, end) => {
    const index = (start + end) / 2 >> 0
    if (index < 0 || index >= len || start > end) return -1
    const curr = nums[index]
    if (curr > target) {
      return fn(start, index - 1)
    } else if (curr < target) {
      return fn(index + 1, end)
    } else {
      return index
    }
  }
  return fn(0, len - 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant