Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sunny-117 opened this issue Nov 3, 2022 · 7 comments
Open

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

Sunny-117 opened this issue Nov 3, 2022 · 7 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@mengqiuleo
Copy link

给定一个升序整数数组[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))

@veneno-o
Copy link
Contributor

veneno-o commented Mar 11, 2023

// 双指针处理临界值问题
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;
}

@yrui-ql
Copy link

yrui-ql commented Apr 20, 2023

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;
}

@QdabuliuQ
Copy link

    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
    }

@kangkang123269
Copy link

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]));

@tyust512
Copy link

构造一个二维数组,遍历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));

@gswysy
Copy link

gswysy commented Feb 28, 2024

只需要遍历一次数组即可,时间复杂度为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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants