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

228. Summary Ranges

时间:2015-11-26 06:57:47      阅读:136      评论:0      收藏: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"].

链接: http://leetcode.com/problems/summary-ranges/

题解:

总结Range。也是从头到尾走一遍。当nums[i] - 1> nums[i - 1],我们处理之前的数字们。当遍历到最后一个元素的时候也要考虑如何处理。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();
        if(nums == null || nums.length == 0)
            return res;
        int lo = 0;
        StringBuilder sb = new StringBuilder();
        
        for(int i = 0; i < nums.length; i++) {
            if(i > 0 && (nums[i] - 1 > nums[i - 1])) {
                if(lo == i - 1)
                    res.add(Integer.toString(nums[lo]));
                else {
                    res.add(sb.append(nums[lo]).append("->").append(nums[i - 1]).toString());
                    sb.setLength(0);
                }
                lo = i;
            }
            
            if(i == nums.length - 1) {
                if(lo == i)
                    res.add(Integer.toString(nums[lo]));
                else
                    res.add(sb.append(nums[lo]).append("->").append(nums[i]).toString());
            }
        }
        
        return res;
    }
}

 

Reference:

https://leetcode.com/discuss/42229/10-line-c-easy-understand

https://leetcode.com/discuss/42199/6-lines-in-python

https://leetcode.com/discuss/42342/idea-1-liner-group-by-number-index

https://leetcode.com/discuss/42290/accepted-java-solution-easy-to-understand

 

228. Summary Ranges

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/4996505.html

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