Skip to content

Latest commit

 

History

History
86 lines (70 loc) · 1.65 KB

704.二分查找.md

File metadata and controls

86 lines (70 loc) · 1.65 KB

704. 二分查找

url

题目

给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target  ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。

输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1

方法

code

js

let search = (nums, target) => {
    if (nums === null || nums.length === 0)
        return -1;
    let l = 0, h = nums.length - 1;
    while (l <= h) {
        let m = l + Math.floor((h - l) / 2);
        if (nums[m] === target)
            return m;
        else if (nums[m] < target)
            l = m + 1;
        else
            h = m - 1;
    }
    return -1;
};
console.log(search([-1,0,3,5,9,12], 9))
console.log(search([-1,0,3,5,9,12], 2))

go

func search(nums []int, target int) int {
	if nums == nil || len(nums) == 0 {
		return -1
	}
	l, h := 0, len(nums) - 1
	for l <= h {
		m := l + (h - l) / 2
		if nums[m] == target {
			return m
		} else if nums[m] < target {
			l = m + 1
		} else {
			h = m - 1
		}
	}
	return -1
}

java

class Solution {
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) return -1;
        int l = 0, h = nums.length - 1;
        while (l <= h) {
            int m = l + (h - l) / 2;
            if (nums[m] == target) return m;
            else if (nums[m] < target) l = m + 1;
            else h = m - 1;
        }
        return -1;
    }
}