Leetcode做题笔记

Leetcode笔记——Search for a range

2019-01-08  本文已影响0人  Scaryang

Problem

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4].

Solution (JAVA)

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        // 找到左边界
        int front = search(nums, target, "front");
        // 找到右边界
        int rear = search(nums, target, "rear");
        int[] res = {front, rear};
        return res;
    }
    
    public int search(int[] nums, int target, String type){
        int min = 0, max = nums.length - 1;
        while(min <= max){
            int mid = min + (max - min) / 2;
            if(nums[mid] > target){
                max = mid - 1;
            } else if(nums[mid] < target){
                min = mid + 1;
            } else {
                // 对于找左边的情况,要判断左边的数是否重复
                if(type == "front"){
                    if(mid == 0) return 0;
                    if(nums[mid] != nums[mid - 1]) return mid;
                    max = mid - 1;
                } else {
                // 对于找右边的情况,要判断右边的数是否重复
                    if(mid == nums.length - 1) return nums.length - 1;
                    if(nums[mid] != nums[mid + 1]) return mid;
                    min = mid + 1;
                }
            }
        }
        //没找到该数返回-1
        return -1;
    }
}

Discussion

这道题的本质是就是找到相同值的上下限位置,基本的方法就是二分查找。在找到第一个值之后,我们需要确定这个值的上下位置。在子区间中,我们既可以继续使用二分查找,也可以使用线性的查找方式。(这里的结局方案显然是使用了二分的方式)

上一篇下一篇

猜你喜欢

热点阅读