228. 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"].
链接: http://leetcode.com/problems/summary-ranges/
7/24/2017
55%
注意,
1. 第9行判断时,nums[i - 1] + 1和nums[i]判断能避免溢出情况。
2. String.valueOf(Int)终于会使用了。
3. 第18-22行将剩余的一组加到结果中
1 public class Solution { 2 public List<String> summaryRanges(int[] nums) { 3 List<String> result = new ArrayList<>(); 4 if (nums == null || nums.length == 0) { 5 return result; 6 } 7 int start = nums[0]; 8 for (int i = 1; i < nums.length; i++) { 9 if (nums[i - 1] + 1 < nums[i]) { 10 if (nums[i - 1] == start) { 11 result.add(String.valueOf(start)); 12 } else { 13 addRange(result, start, nums[i - 1]); 14 } 15 start = nums[i]; 16 } 17 } 18 if (nums[nums.length - 1] == start) { 19 result.add(String.valueOf(start)); 20 } else { 21 addRange(result, start, nums[nums.length - 1]); 22 } 23 return result; 24 } 25 private void addRange(List<String> result, int start, int end) { 26 StringBuilder sb = new StringBuilder(); 27 sb.append(String.valueOf(start)); 28 sb.append("->"); 29 sb.append(String.valueOf(end)); 30 result.add(sb.toString()); 31 } 32 }
官方解答
官方解答更好,因为
1.用了2个index更直观,比较的话只需要比较i,j是否相同即可。
2. 加到result的方法更好
summary.add(nums[i] + "->" + nums[j]);
https://leetcode.com/problems/summary-ranges/#/solution
别人的答案
高阶python用法。。。用于欣赏吧
https://discuss.leetcode.com/topic/17094/6-lines-in-python
https://discuss.leetcode.com/topic/17177/idea-1-liner-group-by-number-index
更多讨论