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

大体思路:设置一个头尾指针,指向待查找range的头和尾,若nums[i+1]-nums[i]==1,则头不动,尾指针+1,否则找到一个range加入list中。代码如下:

 

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> list = new ArrayList<String>();
        int start = 0;//
        int end = 0;//
        if(nums.length==0) return list;
        for(int i=0;i<nums.length-1;i++) {
            if(nums[i+1]-nums[i]==1) {
                end++;
            }
            else {
                if(start==end) list.add(nums[start]+"");
                else list.add(nums[start]+"->"+nums[end]);
                start = i+1;
                end = i+1;
            }
        }
        if(start==end) list.add(nums[start]+"");
        else list.add(nums[start]+"->"+nums[end]);
        return list;
    }
}

 

posted @ 2015-06-26 13:41  mrpod2g  阅读(177)  评论(0编辑  收藏  举报