zoukankan      html  css  js  c++  java
  • leetcode[163] Missing Ranges


    给定一个排好序的数组,和一个区间[lower, upper], 返回丢失的区间范围。例如:

    For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99, return ["2", "4->49", "51->74", "76->99"].

    这里才发现c++版本的。

    string& makeRange(int lo, int hi){
        static string result;
        result="";
        stringstream ss;
        if (lo != hi){
            ss << lo << "->" << hi;
        }else{
            ss << lo;
        }
        ss >> result;
        return result;
    }
    
    
    vector<string> findMissingRanges(int A[], int n, int lower, int upper) {
    
        vector<string> result;
    
        if ( n<=0 ) {
            result.push_back(makeRange(lower, upper));
            return result;
        }
    
        if (lower < A[0]){
            result.push_back(makeRange(lower, A[0]-1 < upper ? A[0]-1 : upper));
        }
    
        for(int i=0; i<n-1; i++){
            if ( A[i] + 1 == A[i+1] ) {
                continue;
            }
            result.push_back(makeRange(A[i]+1, A[i+1]-1));
        }
    
        if (upper > A[n-1]){
            result.push_back(makeRange(A[n-1]+1, upper));
        }
    
        return result;
    }
    View Code

    就是先判断A[0]和lower的值,然后一个循环到n-1,一次输出符合要求的区间,最后还要判断A[n-1]和upper的值。

  • 相关阅读:
    noexcept(c++11)
    右值引用和std::move函数(c++11)
    mint-ui 取值
    apicloud 注意事项
    倒计时
    获取第n天日期
    防止split没有切割的变量报错
    return
    时间戳转为日期
    echarts 中 请求后台改变数据
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4189381.html
Copyright © 2011-2022 走看看