[LeetCode] 34. Search for a Range

题:https://leetcode.com/problems/search-for-a-range/description/

题目

Given an array of integers sorted in ascending order, 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].

思路

原创

1.时间复杂度为O(log n) 说明必须使用,二分查找等方法。
2.通过二分查找找到target在数组中的位置,若未找到直接返回{-1 ,-1}
3.确定target的index后,分别向左向右遍历,查找target的左右边界。

code

import java.util.Vector; 
class Solution {
    public int[] searchRange(int[] nums, int target) {
        int lo=0,hi = nums.length-1;
        int mid = 0;
        boolean flag = true;
        while(lo<=hi){
            mid = (lo+hi)/2;
            if(nums[mid]==target){
                flag = false;
                break;
            }
            else if(nums[mid]>target)   hi = mid-1;
            else    lo = mid + 1;
        }
        if(flag){
            int []arrayresult = {-1,-1};
            return arrayresult;
        };

        int leftindex = mid - 1;
        while (leftindex >= 0 && nums[leftindex] == target){
            leftindex = leftindex - 1;
        }
        leftindex += 1;
        int rightindex = mid + 1;
        while(rightindex <= nums.length - 1 && nums[rightindex] == target){
            rightindex = rightindex + 1;
        }
        rightindex -= 1;

        int []arrayresult = new int[2];
        arrayresult[0] = leftindex;
        arrayresult[1] = rightindex;

        return arrayresult;

    }
}

转载 leedcode 中的答案

1.通过二分查找target的边界。参考注释

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int []arrayresult = {-1,-1};

        // Search for the left one
        int lo=0,hi = nums.length-1;
        while(lo<hi){
            int mid = (lo+hi)/2;
            if(nums[mid]<target)    lo = mid + 1;
            else hi = mid;
        }
        if(nums.length==0 || nums[lo]!= target)   return arrayresult;
        arrayresult[0] = lo;
        // Search for the right one
        lo = 0;
        hi =  nums.length-1;
        while(lo<hi){
            int mid = (lo+hi+1)/2;    // Make mid biased to the right
            if(nums[mid]>target) hi = mid -1;
            else lo = mid;    // So that this won't make the search range stuck.
        }
        arrayresult[1]  = hi;
        return arrayresult;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值