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

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

public static int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        result[0] = findFirst(nums, target);
        result[1] = findLast(nums, target);
        return result;
    }

    private static int findFirst(int[] nums, int target){
        int idx = -1;
        int start = 0;
        int end = nums.length - 1;
        while(start <= end){
            int mid = (start + end) / 2;
            if(nums[mid] >= target){
                end = mid - 1;
            }else{
                start = mid + 1;
            }
            if(nums[mid] == target) idx = mid;
        }
        return idx;
    }

    private static int findLast(int[] nums, int target){
        int idx = -1;
        int start = 0;
        int end = nums.length - 1;
        while(start <= end){
            int mid = (start + end) / 2;
            if(nums[mid] <= target){
                start = mid + 1;
            }else{
                end = mid - 1;
            }
            if(nums[mid] == target) idx = mid;
        }
        return idx;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,778评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,940评论 0 23
  • 股市有宝早来财好 向劳动人民致敬 中安消复牌不但带来了收购波兰安防公司的利好,也带回来一个ST的帽子,这迫使持有该...
    夏雪_d5b3阅读 220评论 0 0
  • 记忆在我心融化 而你看不见 而你看不见 我心在暗里流泪 不是蛟人泣珠 只是如下雨的天 那种 无人止步的悲
    汪陈阅读 329评论 0 2
  • 太阳还很炙烈, 小小的蚊蠓已经一团团地占据树荫, 低头族无知无觉地乱走, 也冲不散它们的方阵。 走路的时候, 把手...
    读云轩札记阅读 264评论 0 0