文章 212
评论 2
浏览 124957
Array - 228. Summary Ranges

Array - 228. Summary Ranges

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

思路:

把一个数组连续的字串变成0->3,单独的间断点就没有->这样一个字符串有序表。思路就是遍历数组,记录数组连续的开始点(间断点的下一位)。然后判断间断点加入链表就可以。

代码:

java:

class Solution {

    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();
        int start = 0;
        if (nums == null | nums.length == 0) return res;
        for (int i = 0; i < nums.length; i++) {
            if (i < nums.length - 1 && nums[i] + 1 == nums[i + 1]) continue;
            if (start == i){ // 间断点的起点
              res.add(nums[i] + "");  
            } else {
                res.add(nums[start] + "->" + nums[i]);
            }
            start = i + 1;
        }
        
        return res;
    }
}


标题:Array - 228. Summary Ranges
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/25/1561473426016.html

Nothing just happens, it's all part of a plan.

取消