Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

["0->2", "4->5", "7", "13", "15->16"]

Sunny-117 opened this issue · comments

["0->2", "4->5", "7", "13", "15->16"]
commented

给定一个升序整数数组[0,1,2,4,5,7,13,15,16],找出其中连续出现的数字区间如下:
["0->2","4->5","7","13","15->16"]

const arr = [0, 1, 2, 4, 5, 7, 13, 15, 16]

function getArr(arr) {
  let j, ans = [], str = '';
  for (let i = 0; i < arr.length; i++) {
    j = i;
    if (arr[i] + 1 === arr[i + 1]) {
      while (arr[j] + 1 === arr[j + 1]) {
        str = '->' + arr[j + 1];
        j++;
      }
      str = arr[i] + str;
      ans.push(str)
      i = j
    } else {
      ans.push(arr[i].toString());
    }
  }
  return ans;
}


console.log(getArr(arr))
// 双指针处理临界值问题
function format(arr){
    const len = arr.length;
    const res = [];
    let pre = 0, cur = 0;

    for(cur = 0; cur < len; ++cur){
        if(cur === pre || arr[cur] === arr[cur - 1] + 1){continue};
        if(cur - pre === 1){
            res.push(Number(arr[pre]).toString());
        }else{
            res.push(Number(arr[pre]).toString() + "->" + Number(arr[cur - 1]).toString())
        }
        pre = cur;
    }
    
    // 处理临界值
    if(pre === cur){
        res.push(Number(arr[pre]).toString());
    }else{
        res.push(Number(arr[pre]).toString() + "->" + Number(arr[len - 1]).toString())
    }
    return res;
}
commented
function summaryRanges(arr) { 
    if (arr.length < 1) {
        return [ ];
    }
    const ans = [];
    let slow = 0;
    let fast = 1;
    while (fast !== arr.length + 1) {
        if (arr[fast] - arr[fast - 1] !== 1 || arr.length === fast) {
            if (arr[slow] === arr[fast - 1]) {
                ans.push(arr[slow] + '');
            } else {
                ans.push(arr[slow] + '->' + arr[fast - 1]);
            }

            slow = fast;
        }

        fast++;
    }

    return ans;
}
    function convey(arr) {
      let res = []
      let i = 0
      while(i < arr.length) {
        let j = i
        while(j < arr.length-1 && arr[j] === arr[j+1]-1) {
          j ++
        }
        if(j === i) {
          res.push(arr[i].toString())
          i ++
        } else {
          res.push(`${arr[i]}->${arr[j]}`)
          i = j+1
        }
      }
      return res
    }
function findConsecutiveRanges(arr) {
    var result = [];
    for (var i = 0; i < arr.length; i++) {
        var start = arr[i];
        while (arr[i] + 1 === arr[i + 1]) { // 检查当前数字和下一个数字是否连续
            i++;
        }
        var end = arr[i];
        if (start !== end) { 
            result.push(start + "->" + end); // 如果序列有多个数字,则添加范围
        } else {
            result.push(start.toString()); // 如果序列只有一个数字,则直接添加该数字
        }
    }
    return result;
}

console.log(findConsecutiveRanges([0,1,2,4,5,7,13,15,16]));

构造一个二维数组,遍历2次即可

const arr = [0, 1, 2, 4, 5, 7, 13, 15, 16];

function getRangeList(arr) {
  if (!arr.length) return "";
  if (arr.length === 1) return arr[0];

  const list = [[]];
  let i = 0;
  arr.forEach((item) => {
    list[i] = list[i] || [];

    if (!list[i].length) list[i].push(item);
    else {
      const theLast = list[i][list[i].length - 1];
      if (item - theLast > 1) {
        i++
      }

      list[i] = list[i] || [];
      list[i].push(item)
    }
  });

  // console.log(list)

  return list.map(itemList => {
    if (itemList.length === 1) return itemList[0]
    return `${itemList[0]}->${itemList[itemList.length-1]}`
  }).join(',')
}

console.log(getRangeList(arr));

只需要遍历一次数组即可,时间复杂度为O(n)

function format(arr) {
  let res = []
  let pre = arr[0], //记录上一个
    s = arr[0], //标记起点
    key = false //是否为连续
  for (let i = 1; i < arr.length; i++) {
    if (arr[i] === pre + 1) {
      key = true
    } else {
      if (key) {
        res.push(s + '->' + pre)
      } else {
        res.push(pre)
      }
      s = arr[i]
      key = false
    }
    pre = arr[i]
    if (i === arr.length - 1) { //处理最后一个元素
      if (key) {
        res.push(s + '->' + pre)
      } else {
        res.push(pre)
      }
    }
  }
  return res
}