zoukankan      html  css  js  c++  java
  • Summary Ranges

    题目:

    Given a sorted integer array without duplicates, return the summary of its ranges.

    For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

    cpp:

    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> result;
            if (nums.empty())
                return result;
    
            int start = nums[0];
            int end = nums[0];
    
            int len = nums.size();
            for (int i = 1; i < len; i++) {
                if ( nums[i] == nums[i - 1] || nums[i] == (nums[i-1]+1)) {
                    end = nums[i];
                } else {
                    result.push_back(format(start,end));
                    start = nums[i];
                    end = start;
                }
            }
            result.push_back(format(start,end));
            return result;
        }
    
    //    string format(int begin,int end){
    //        char buffer[32];
    //        if(begin == end){
    //            sprintf(buffer,"%d",begin);
    //        }else{
    //            sprintf(buffer,"%d->%d",begin,end);
    //        }
    //        return string(buffer);
    //    }
        
        string format(int begin,int end){
            stringstream ss;
            if(begin == end){
                ss << begin;
            }else{
                ss << begin << "->" << end;
            }
            return ss.str();
        }
    };

    python:

    class Solution(object):
        def summaryRanges(self, nums):
            x, size = 0, len(nums);
            result = []
            while x < size:
                c, r = x, str(nums[x])
                while x + 1 < size and nums[x + 1] == nums[x] + 1:
                    x += 1
                if x > c:
                    r += "->" + str(nums[x])
                result.append(r)
                x += 1
            return result; 
            
  • 相关阅读:
    Python---Flask--08--Flask-Ckeditor
    Python---Flask--07--SQLAlchemy基本关系
    Python---Flask--06--分页的实现
    Python---Flask--05--g对象和钩子函数
    maven项目管理构建
    POI 设置
    http状态码
    hibernate框架之-查询结果集返回类型
    Struts2框架之-注解开发
    Struts2框架之-Struts2的标签
  • 原文地址:https://www.cnblogs.com/wxquare/p/5222121.html
Copyright © 2011-2022 走看看