【问题标题】:Javascript check rising trend in tableJavascript检查表格中的上升趋势
【发布时间】:2020-07-15 20:51:44
【问题描述】:

给定一个整数序列作为一个数组,确定是否可以通过从数组中删除不超过一个元素来获得一个严格递增的序列。 我创建了这段代码

function almostIncreasingSequence(sequence) {

    let index;
    let licznik = 0;

    for (index = 1; index < sequence.length; index++) {
        
        
          if (sequence[index - 1] >= sequence[index]) {
            sequence.splice(index - 1, 1);
            licznik++;
            index = 0;
        } else if (sequence[index] > sequence[index + 1]) {
           sequence.splice(index + 1, 1);
            licznik++;
            index = 0;
        }
    }

    if (licznik > 1) {
        return false;
    } else {
        return true;
    }

}

但它不适用于表 [1, 2, 3, 4, 99, 5, 6]。有什么建议吗?

【问题讨论】:

  • 开始,请“return licznik > 1”。
  • 在你的 else 上,你删除了 5,而不是 99。你应该在 index 位置而不是 index + 1 上拼接项目。但请注意,您在此问题上的方法不起作用,例如使用简单的 [5, 95, 96, 6, 97],因为删除 6 足以返回 true,但您的方法将先删除 96。
  • 最后一个帖子在哪里?前两天看到了,现在看不到了
  • @punund return licznik &lt;= 1

标签: javascript arrays


【解决方案1】:

您已经接近解决方案,使用 splice 方法您必须遍历您的数组执行三个步骤:

  1. 使用splice在每一步删除一个元素。
  2. 检查得到的新数组是否排序,是否返回 值true
  3. 将删除的元素插入到相同的位置,重新创建 原始数组。

第二步比较几个数组元素并在找到几个元素时停止,例如sequence[i] &gt; sequence[i + 1];

function almostIncreasingSequence(sequence) {

    for (let index = 0; index < sequence.length; ++index) {
        const removed = sequence.splice(index, 1);
        let sorted = true;

        for (let j = 0; j < sequence.length - 1; ++j) {

            if (sequence[j] > sequence[j + 1]) {
                sorted = false;
                break;
            }

        }

        if (sorted) { return true; }

        sequence.splice(index, 0, removed);

    }

    return false;

}

console.log(almostIncreasingSequence([1, 2, 3, 4, 99, 5, 6]));

【讨论】:

    猜你喜欢
    • 2014-07-30
    • 2021-07-15
    • 2020-11-12
    • 2019-01-31
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多