LeetCode 228. Summary Ranges(归纳区间)

原题网址:https://leetcode.com/problems/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"].

思路:对每个元素,如果与上一个区间的右端点相差1,则合并区间,否则新开一个区间。

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        Range[] ranges = new Range[nums.length];
        int size = 0;
        for(int i=0; i<nums.length; i++) {
            if (i > 0 && ranges[size-1].to + 1 == nums[i]) ranges[size-1].to ++;
            else ranges[size++] = new Range(nums[i], nums[i]);
        }
        List<String> results = new ArrayList<String>();
        for(int i=0; i<size; i++) {
            if (ranges[i].from == ranges[i].to) results.add(Integer.toString(ranges[i].from));
            else results.add(Integer.toString(ranges[i].from) + "->" + Integer.toString(ranges[i].to));
        }
        return results;
    }
}
class Range {
    int from, to;
    Range(int from, int to) {
        this.from = from;
        this.to = to;
    }
}

另一种类似的方法:

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> ranges = new ArrayList<>();
        if (nums == null || nums.length == 0) return ranges;
        int[] range = new int[] {nums[0], nums[0]};
        for(int i=1; i<=nums.length; i++) {
            if (i<nums.length) {
                if (range[1]+1 == nums[i]) {
                    range[1] = nums[i];
                } else {
                    if (range[0] == range[1]) ranges.add(Integer.toString(range[0]));
                    else ranges.add(Integer.toString(range[0]) + "->" + Integer.toString(range[1]));
                    range[0] = nums[i];
                    range[1] = nums[i];
                }
            } else {
                if (range[0] == range[1]) ranges.add(Integer.toString(range[0]));
                else ranges.add(Integer.toString(range[0]) + "->" + Integer.toString(range[1]));
            }
        }
        return ranges;
    }
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jmspan/article/details/51062065
文章标签: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭