zoukankan      html  css  js  c++  java
  • LeetCode 34. Search for a Range Java

    题目:

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

    题意:给出一个升序排列的数组,其中可能有重复的元素。给出一个target,在数组中查找,若查找到则返回数组中该元素开始的坐标和结束的index(如果其中只有一个元素匹配,则返回的开始和结束index相同,例如[3,3]);若不存在则返回[-1,-1]。我采用的方法是直接对数组进行二分查找,若查找到元素,则对该位置分别向前和向后查找,直到和target不相等;如没有查找到元素则直接返回[-1,-1]. 但是这样做的最差复杂度为0(n),所以可以使用两个二分查找分别查找最左的target和最右的target,然后相减即可。

    代码:

    public int[] searchRange(int[] A, int target) {
            int [] res = {-1,-1};
            if(A == null || A.length == 0)
                return res;
            
            //first iteration, find target wherever it is
            int low = 0;
            int high = A.length-1;
            int pos = 0;
            while(low <= high){
                int mid = (low + high)/2;
                pos = mid;
                if(A[mid] > target)
                    high = mid - 1;
                else if(A[mid] < target)
                    low = mid + 1;
                else{
                    res[0] = pos;
                    res[1] = pos;
                    break;
                }
            }
            
            if(A[pos] != target)
                return res;
            
            //second iteration, find the right boundary of this target
            int newlow = pos;
            int newhigh = A.length-1;
            while(newlow <= newhigh){
                int newmid = (newlow+newhigh)/2;
                if(A[newmid] == target)
                    newlow = newmid + 1;
                else
                    newhigh = newmid - 1;
            }
            res[1] = newhigh;
            
            //third iteration, find the left boundary of this target
            newlow = 0;
            newhigh = pos;
            while(newlow <= newhigh){
                int newmid = (newlow+newhigh)/2;
                if(A[newmid] == target)
                    newhigh = newmid - 1;
                else
                    newlow = newmid + 1;
            }
            res[0] = newlow;
            
            return res;
        }
  • 相关阅读:
    css3-响应式布局
    css3-盒模型新增属性
    css3-弹性盒模型
    阿里天池超级码力复赛
    [状态压缩dp]Leetcode5.02双周赛 每个人戴不同帽子的方案数
    算法编程题:魔塔
    [Dijkstra贪心思想妙用]真实笔试题:传送门
    2020 力扣杯!Code Your Future 春季全国编程大赛 个人赛
    经典笔试算法题之打小怪兽
    两道经典面试算法题2020-3-20(打牌,最长上升字符串拼接)
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6902242.html
Copyright © 2011-2022 走看看