Skip to content

Latest commit

 

History

History
110 lines (91 loc) · 2.37 KB

34.在排序数组中查找元素的第一个和最后一个位置.md

File metadata and controls

110 lines (91 loc) · 2.37 KB

34. 在排序数组中查找元素的第一个和最后一个位置

url

题目

给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

如果数组中不存在目标值 target,返回 [-1, -1]。

输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
输入:nums = [], target = 0
输出:[-1,-1]

方法

code

js

let searchRange = (nums, target) => {
    let findFirst = (nums, target) => {
        let l = 0, h = nums.length; // h的初始值和往常不一样
        while (l < h) {
            let m = l + Math.floor((h - l) / 2);
            if (nums[m] >= target)
                h = m;
            else
                l = m + 1;
        }
        return l;
    };

    let first = findFirst(nums, target);
    let last = findFirst(nums, target + 1) - 1;
    if (first === nums.length || nums[first] !== target)
        return [-1, -1];
    else
        return [first, Math.max(first, last)];
};

go

func searchRange(nums []int, target int) []int {
	findFirst := func (nums []int, target int) int {
		l, h := 0, len(nums)
		for l < h {
			m := l + (h-l)/2
			if nums[m] >= target {
				h = m
			} else {
				l = m + 1
			}
		}
		return l
	}
	Max := func(a int, b int) int {
		if a < b {
			return b
		} else {
			return a
		}
	}
	first := findFirst(nums, target)
	last := findFirst(nums, target + 1) - 1
	if first == len(nums) || nums[first] !=target {
		return []int{-1, -1}
	} else {
		return []int{first, Max(first, last)}
	}
}

java

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int first = findFirst(nums, target);
        int last = findFirst(nums, target + 1) - 1;
        if (first == nums.length || nums[first] != target) {
            return new int[] {-1, -1};
        } else {
            return new int[]{first, Math.max(first, last)};
        }
    }
    private int findFirst(int[] nums, int target) {
        int l = 0, h = nums.length; // h 的初始值和往常不一样
        while (l < h) {
            int m = l + ( h - l) / 2;
            if (nums[m] >= target) h = m;
            else l = m + 1;
        }
        return l;
    }
}