【小算法】相连数字数组,用横杠起止简写

8178次浏览

前言

本题是工作中用到的一个小的算法题目,刚刚做的时候,走了一下弯路,其实思路对了,解起来很简单。下面来解析一下。后期我会整理一份常用的算法题目,每个题目都会录制成视频,和大家一起分享解题思路。有些也会借鉴leecode中的一些题目。

题目

// 一组数字,相连的用-拼接,不相连的直接写数字本身,
//例如[1,3,4,5,8,9,12,13,14,15,20]可以写成1;3-5;8-9;12-15;20这种形式。

思路

1、先把数组按照从小到大排序

2、找出数字开始位置

3、找出数字结束位置

4、开始和结束用横杠拼接

标注数字开始位置

以 [1,3,4,5,8,9,12,13,14,15,20]这个数组为例,1 前后无相连,直接放到新的数组里面,3,前面无相连,后面有相连的,为起始值,标注为开始位置。

标注结束位置

数组5,前面有相连的4,后面无相连,标注为结束位置。

解题代码

let Arry=[1,3,4,5,8,9,12,13,14,15,20]

//需求,一组数字相连的用-链接,然后用;拼接起来

const handleNumberArray =(Arry)=>{

  let start =''
  let result =[]
  Arry = Arry.sort((a,b)=>a-b)
  Arry.forEach((item,index)=>{
    if(item+1 == Arry[index+1] && item-1 !=Arry[index-1]){
      start = item // 标注开始位置
    } else if(item-1 == Arry[index-1] && item+1 != Arry[index+1]) {
      result.push(`${start}-${item}`)// 结束位置的时候放到数组里面

    } else if(item-1 != Arry[index-1] && item+1 != Arry[index+1]){
      result.push(item)// 前后不相连,放到数组里面
    }
  })
  return result.join(';')
}

相关视频

小算法

推荐视频

1、js的proto和prototype区别

2、秒懂js的constructor

相关文章:

  1. Steve
    1
    I was looking at your website and noticed it appears the word "const" is spelled wrong. I had similar problems on my site until someone mentioned it to me and I also now use software from SpellPerfect.com to keep my site error free.