8

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

 3 years ago
source link: https://www.haorooms.com/post/number_gang_contact
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

2021年3月31日 215次浏览

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

敬请期待~~

相关文章:

  • 亲,未找到相关文章哦!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK