xinchanghao / one-day-in-the-future

有朝一日,起飞...
2 stars 1 forks source link

合并数组中的连续数字 #19

Open xinchanghao opened 4 years ago

xinchanghao commented 4 years ago

我写的垃圾算法,求diss哈哈哈哈哈啊哈哈

实现一个函数:

function _sort(arr) {
  if (arr.length <= 0) {
    return arr;
  }

  const _arr = [...new Set(arr)].sort((a, b) => a - b);
  let res = [];
  let index = 0;

  for (let i = 0; i < _arr.length; i++) {
    if (!res[index]) {
      res[index] = [];
    }

    if (_arr[i] - _arr[i - 1] === 1) {
      res[index].push(_arr[i]);
    } else {
      index++;
      res[index] = [_arr[i]];
    }
  }

  res = res.filter((i) => i.length !== 0);

  res = res.map((i) => {
    if (i.length > 1) {
      return `${i[0]}-${i[i.length - 1]}`;
    } else {
      return i[0];
    }
  });

  return res;
}
pzli commented 4 years ago

function func(nums) {
  if(nums.length == 0) return []
  nums = nums.sort((a, b) => a - b)
  let res = [{
    cur: nums[0],
    str: nums[0] + ''
  }]
  nums.slice(1).forEach(item=>{
    let resCur = res[res.length - 1]
    if(item - resCur.cur <= 1) {
      resCur.cur = item;
      if(resCur.str.includes('->')) {
        resCur.str = resCur.str.split('->')[0] + '->' + item
      }else {
        resCur.str = resCur.str + '->' + item
      }
    }else {
      res.push({
        cur: item,
        str: item + ''
      })
    }
  })
  return res.map(item => item.str)
}
xinchanghao commented 4 years ago

@pzli 你咋这么骚呢?