码迷,mamicode.com
首页 > 其他好文 > 详细

汇总区间

时间:2020-07-29 21:32:53      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:push   length   let   组成   col   color   span   连续   解释   

给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。

输入: [0,1,2,4,5,7]

输出: ["0->2","4->5","7"]

解释: 0,1,2 可组成一个连续的区间; 4,5 可组成一个连续的区间。

function summaryRanges(nums) {
    let pre = nums[0],next = nums[0],arr = [];
    if(nums.length == 0){
        return arr
    }
    for(let i = 1;i < nums.length;i++){
        let item = nums[i]
        if(item - next <= 1){
            next = item
        }else{
            if(pre == next){
                arr.push(pre+‘‘)
            }else{
                arr.push(pre +‘->‘+next)
            }
            pre = item
            next = item
        }
    }
    if(pre == next){
        arr.push(pre+‘‘)
    }else{
        arr.push(pre +‘->‘+next)
    }
    return arr
} 

Leecode提交通过

 

汇总区间

标签:push   length   let   组成   col   color   span   连续   解释   

原文地址:https://www.cnblogs.com/zhenjianyu/p/13399376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!