码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 228: Summary Ranges

时间:2015-06-26 06:53:55      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

Summary Ranges

Total Accepted: 511 Total Submissions: 2271

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

[思路]

两个指针 start, end.  如果nums[end+1] = nums[end]+1, 就移动end指针, 否则, 插入字符串nums[start]->nums[end].

[CODE]

public class Solution {
    // [0,1,2,4,5,7], return ["0->2","4->5","7"]. 
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();
        if(nums==null || nums.length<1) return  res;
        
        int s=0, e=0;
        while(e<nums.length) {
            if(e+1<nums.length && nums[e+1]==nums[e]+1) {
                e++;
            } else {
                if(s==e) {
                    res.add(Integer.toString(nums[s]));
                } else {
                    String str = nums[s] + "->" + nums[e];
                    res.add(str);
                }
                ++e;
                s = e;
            }
        }
        return res;
    }
}




leetcode 228: Summary Ranges

标签:

原文地址:http://blog.csdn.net/xudli/article/details/46645087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!