zoukankan      html  css  js  c++  java
  • [LeetCode#34]Search for a Range

    The problem:

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

    My analysis:

    The idea behind this question is very elegant and tricky.
    key: when the target value is found, we are not return it (very important). we keep going to reach the the boundry.
    It's very skllful to write the right checking condition, and read the right value from the proper pointer.
    1. When we reach the the left most target, we stop the low pointer(left pointer).
    if (A[mid] < target) //we move the low pointer only when A[mid] is strictly smaller than target.
    low = mid + 1;
    else //A[mid] <= target, we keep move high pinter, even when A[mid] == target.
    high = mid - 1

    2. The same idea could be used to find the right most target, we stop the high pointer(right pointer).
    if (A[mid] <= target)
    low = mid + 1;
    else //A[mid] > target, we move high pointer only when A[mid] is strictly larger than target.
    high = mid - 1;

    My solution:

    public class Solution {
        public int[] searchRange(int[] A, int target) {
            
            int[] ret = new int[2];
            ret[0] = -1;
            ret[1] = -1;
            
            if (A.length == 0)
                return ret;
            
            int llow = 0;
            int lhigh = A.length - 1;
            int rlow = 0;
            int rhigh = A.length - 1;
            int mid = -1;
            
            while (llow <= lhigh) {
                mid = (llow + lhigh) / 2;
                
                if (A[mid] < target) //the idea behind this approaching is very tricky and elegant!
                    llow = mid + 1;
                else 
                    lhigh = mid - 1;
            }
            
            while (rlow <= rhigh) {
                mid = (rlow + rhigh) / 2;
                
                if (A[mid] <= target)
                    rlow = mid + 1;
                else 
                    rhigh = mid - 1;
            }
            
            if (llow <= rhigh) {
                ret[0] = llow;
                ret[1] = rhigh;
            }
            
            return ret; 
        }
    }
  • 相关阅读:
    kafka学习3——单机伪集群(window版)
    (转)在阿里云 CentOS 服务器(ECS)上搭建 nginx + mysql + php-fpm 环境
    渗透测试工具sqlmap基础教程
    编译安装nginx后service nginx start 启动不了
    centos6.5上tomcat的安装
    centos6.5上安装淘宝tfs系统
    解决nagios登录不了的问题
    centos6.5上网络不通解决方法
    redis远程密码连接
    centos7上定时将mysql数据导出并且发送到指定的邮箱
  • 原文地址:https://www.cnblogs.com/airwindow/p/4205741.html
Copyright © 2011-2022 走看看