LeetCode 228. Summary Ranges

原题链接在这里:https://leetcode.com/problems/summary-ranges/

题目:

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

题解:

start is starting element, when nums[i] is not cut from nums[i - 1], we need to add a range [start, nums[i - 1]].

Note: Don't forget to add the last range. [start, nums[n - 1].

Time Complexity: O(nums.length).

Space:O(1), regardless res.

AC Java:

 1 class Solution {
 2     public List<String> summaryRanges(int[] nums) {
 3         List<String> res = new ArrayList<>();
 4         if(nums == null || nums.length == 0){
 5             return res;
 6         }
 7         
 8         int n = nums.length;
 9         int start = nums[0];
10         for(int i = 1; i<n; i++){
11             if(nums[i] != nums[i - 1] && nums[i - 1] + 1 != nums[i]){
12                 res.add(getRange(start, nums[i - 1]));
13                 start = nums[i];
14             }
15         }
16         
17         res.add(getRange(start, nums[n - 1]));
18         
19         return res;
20     }
21     
22     private String getRange(int l, int r){
23         return l == r ? "" + l : l + "->" + r;
24     }
25 }

类似Missing RangesData Stream as Disjoint Intervals.

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5139920.html