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

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

        public int[] searchRange(int[] nums, int target) {
            int length = nums.length;
            int low = 0;
            int high = length-1;
            int start,end= 0;
            while (low<=high){
                int middle = (low+high)/2;
                if (nums[middle]==target){
                    start = middle;
                    end = middle;
                    while (start>=0&&nums[start]==target){
                        start--;
                    }
                    start++;
                    while (end<length&&nums[end]==target){
                        end++;
                    }
                    end--;
                    return new int[]{start,end};
                }
                else if (nums[middle]>target){
                    high=middle-1;
                }
                else if (nums[middle]<target){
                    low = middle+1;
                }
            }
            return new int[]{-1, -1};
        }
    
  • 相关阅读:
    2.搭建第一个http服务:三层架构
    1.基础入门
    MyISAM和InnoDB索引区别
    分区
    事务的四大特性
    事务
    String
    自己写native方法
    序列化和反序列化
    反射
  • 原文地址:https://www.cnblogs.com/bingo2-here/p/8288018.html
Copyright © 2011-2022 走看看