• 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};
        }
    
  • 相关阅读:
    红黑树实现
    Java环境变量的配置及意义
    Java 内存分配全面浅析
    吸血鬼数字
    nat模式、路由模式,网桥模式
    WebService 的创建,部署和使用
    摩尔定律
    计算机组成
    世界是数字的
    面试
  • 原文地址:https://www.cnblogs.com/bingo2-here/p/8288018.html
Copyright © 2020-2023  润新知