导航

(easy)LeetCode 228.Summary Ranges

Posted on 2015-07-31 14:39  骄阳照林  阅读(128)  评论(0编辑  收藏  举报

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

代码如下:

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String>list=new ArrayList<String>();
        int len=nums.length;
        if(len==0) return list;
        int begin=nums[0];
        int end=nums[0];
        for(int i=0;i<len;i++){
            begin=nums[i];
            while(i+1<len && nums[i+1]-nums[i]==1)
                 i++;
            end=nums[i];
            String s=null;
            if(begin!=end)
                 s=""+begin+"->"+end;
            else
                 s=""+begin;
            list.add(s);
                 
        }
        return list;
    }
}

  运行结果: