【问题标题】:Max consecutive items of numbers in array with +1 difference数组中最大连续数字项+1差
【发布时间】:2021-08-08 18:34:11
【问题描述】:

我正在尝试返回最大连续数字或相同数字的最大数量,差异不超过 + 1。

示例*

const array = [1,2,3,5,5,6,6,6,6,7,8]
solution= 556666

const array2 = [2,2,3,4,4,5,5]
solution= 4455

我是一个新的编码员,似乎应该有一个更简单的方法来解决这个问题,但我被困在这一点上。

function getMaximumNumberItems(arr) {
    let initial = {'0': 0, '1':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0 }
    let counts = {}
    arr.forEach((element) => {
       counts[element] = (counts[element] || 0) + 1
    })
    const numbers = {...initial,...counts}
    const arrValues = Object.values(numbers)
    let sum = []
    for (let i = 0; i < arrValues.length; i++) {
      arrValues[i] === arrValues[arrValues.length - 1] ? null : sum.push(arrValues[i] + arrValues[i + 1])
    }
    console.log(sum)
    let maxIndex = sum.indexOf(Math.max(...sum))
  }

我所做的是为每个数字设置一个计数 numbers,然后我将每个元素与下一个元素相加,以查看 连续元素的最大数量并将它们添加到数组,即总和。这个最大数的索引也应该是应该从counts返回的第一个元素的索引。

我的想法是从对象返回键并访问该数字出现了多少次并以某种方式添加它,然后以相同的方式使用数字的下一个元素来获得解决方案。

显然,我认为这是最糟糕的做法,因此不胜感激。

谢谢!

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    您可以在O(n) 时间完成。取数字,匹配之后的所有数字,与它的差为1或更小。如果你找到了差大于 1 的数字,那么你需要记住当前结果并重复前面的步骤,确定最佳序列开始的元素的数量和长度。

    function maxSubsequence(array) {
        let ind = 0;
        let bestInd = 0;
        let cnt = 1;
        let maxCnt = 0;
    
        for (let i = 1; i < array.length; i++) {
            if (Math.abs(array[ind] - array[i]) <= 1) {
                cnt++;
            } else {
                if(cnt > maxCnt) {
                    bestInd = ind;
                    maxCnt = cnt;
                }
                cnt = 1;
                ind = i;
            }
        }
    
        if (cnt > maxCnt) {
            bestInd = ind;
            maxCnt = cnt;
        }
    
        return array.slice(bestInd, bestInd + maxCnt);
    }
    

    输出:

    maxSubsequence(array)
    [5, 5, 6, 6, 6, 6]
    
    maxSubsequence(array2)
    [4, 4, 5, 5]
    

    【讨论】:

    • 哇,太棒了,我什至没有接近正确的答案。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-01-28
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2020-01-22
    • 1970-01-01
    相关资源
    最近更新 更多