228 Summary Ranges 汇总区间

给定一个无重复元素的有序整数数组,返回数组中区间范围的汇总。

示例 1:

输入: [0,1,2,4,5,7]
输出: ["0->2","4->5","7"]
示例 2:

输入: [0,2,3,4,6,8,9]
输出: ["0","2->4","6","8->9"]

详见:https://leetcode.com/problems/summary-ranges/description/

Java实现:

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res=new ArrayList<String>();
        int n=nums.length;
        int i=0;
        while(i<n){
            int j=1;
            while(i+j<n&&nums[i+j]-nums[i]==j){
                ++j;
            }
            res.add(j==1?String.valueOf(nums[i]):String.valueOf(nums[i])+"->"+String.valueOf(nums[i+j-1]));
            i+=j;
        }
        return res;
    }
}

C++实现:

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;
        int i=0,n=nums.size();
        while(i<n)
        {
            int j=1;
            while(i+j<n&&nums[i+j]-nums[i]==j)
            {
                ++j;
            }
            res.push_back(j==1?to_string(nums[i]):to_string(nums[i])+"->"+to_string(nums[i+j-1]));
            i+=j;
        }
        return res;
    }
};

参考:https://www.cnblogs.com/grandyang/p/4603555.html

posted on 2018-04-09 11:26  lina2014  阅读(180)  评论(0编辑  收藏  举报

导航