228. 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.

难度:medium

题目:给定排序且无重复元素的整数数组,返回其连续元素的范围。

思路:用以变量记录连续元素的开始。

Runtime: 5 ms, faster than 7.57% of Java online submissions for Summary Ranges.
Memory Usage: 37.5 MB, less than 5.02% of Java online submissions for Summary Ranges.

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<>();
        if (null == nums || nums.length < 1) {
            return result;
        }
        
        for (int i = 1, start = 0; i <= nums.length; i++) {
            if (i == nums.length || nums[i] - nums[i - 1] != 1) {
                result.add((i - 1 == start) ? String.format("%s", nums[start]) 
                    : String.format("%s->%s", nums[start], nums[i - 1]));
                start = i;
            }
        }
        
        return result;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018262523
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞