zoukankan      html  css  js  c++  java
  • Search for a Range ——LeetCode

    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].

    题目大意:给定一个排序好的数组,找到指定数的起始范围,如果不存在返回[-1,-1];

    解题思路:要求O(lgN)时间复杂度,二分查找。

        public int[] searchRange(int[] nums, int target) {
            int[] res = new int[2];
            if(nums==null||nums.length==0){
                return res;
            }
            res[0]=getLow(nums,target,0,nums.length-1);
            res[1]=getHigh(nums,target,0,nums.length-1);
            return res;
        }
        int getLow(int[] nums,int target,int low,int high){
            int mid=(low+high)>>1;
            if(low>high){
                return -1;
            }
            if(low==high){
                return nums[low]==target?low:-1;
            }
            if(nums[mid]==target){
                return getLow(nums,target,low,mid);
            }
            if(nums[mid]<target){
                low=mid+1;
                return getLow(nums,target,low,high);
            }else{
                high=mid-1;
                return getLow(nums,target,low,high);
            }
        }
        int getHigh(int[] nums,int target,int low,int high){
             int mid=(low+high)>>1;
             if(low>high){
                 return -1;
             }
            if(low==high){
                return nums[low]==target?low:-1;
            }
            if(nums[mid]==target){
                int tmp=getHigh(nums,target,mid+1,high);
                int max=Math.max(tmp,mid);
                return max;
            }
            if(nums[mid]<target){
                low=mid+1;
                return getHigh(nums,target,low,high);
            }else{
                high=mid-1;
                return getHigh(nums,target,low,high);
            }
        }
  • 相关阅读:
    11-3 多道批处理系统
    URAL 1108 简单的树形dp背包问题
    POJ 2486 树形dp
    HDU 2242 连通分量缩点+树形dp
    POJ 3140 Contestants Division
    POJ 2378 Tree Cutting
    ZOJ 3201 树形背包问题
    POJ 1655 Balancing Act && POJ 3107 Godfather
    COJ 1351 Tree Counting 动态规划
    codeforces 219D 树形dp
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4560008.html
Copyright © 2011-2022 走看看