标签:
题目:
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
标签:
原文地址:http://www.cnblogs.com/yrbbest/p/4996505.html