美文网首页
228. Summary Ranges

228. Summary Ranges

作者: yxwithu | 来源:发表于2017-08-29 10:29 被阅读0次

    题目

    Given a sorted integer array without duplicates, 
    return the summary of its ranges.
    Input: [0,1,2,4,5,7]
    Output: ["0->2","4->5","7"]
    

    给一个有序数组,将数组中连续的数字的变成range的形式

    分析

    这道题居然是medium难度的让我大跌眼镜。一遍扫描就可以了,具体看代码

    代码

    public List<String> summaryRanges(int[] nums) {
        List<String> list = new ArrayList<>();
        if(nums == null || nums.length == 0) return list;
        int start = nums[0];
        int prev = nums[0];
        int cur = nums[0];
        for(int i = 1; i < nums.length; i ++){
            cur = nums[i];
            if(cur != prev + 1){ //不连续
                String info = start == prev ? "" + start : start + "->" + prev;
                list.add(info);
                start = cur;
            }
            prev = cur;
        }
        list.add(start == prev ? "" + start : start + "->" + prev);
        return list;
    }

    相关文章

      网友评论

          本文标题:228. Summary Ranges

          本文链接:https://www.haomeiwen.com/subject/iuqodxtx.html