leetcode [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.

题目大意:

将数组进行区间合并,返回合并后的区间集合。

解法:

使用两个指针来做。

java:

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String>res=new ArrayList<>();
        Arrays.sort(nums);
        int start=0,end=0;
        while(end<nums.length){
            end++;
            if(end==nums.length || nums[end] > nums[end-1]+1){
                if(nums[start]==nums[end-1]) res.add(String.valueOf(nums[start]));
                else{
                    res.add(String.valueOf(nums[start])+"->"+String.valueOf(nums[end-1]));
                }
                start=end;
            }
        }
        return res;
    }
}
上一篇:CNCF Landscape Summary


下一篇:机器学习技法笔记:11 Gradient Boosted Decision Tree