【问题标题】:left rotation operation for nested loop in jsjs中嵌套循环的左旋转操作
【发布时间】:2021-06-02 11:50:57
【问题描述】:

我想使用嵌套循环对数组进行左旋转操作。

参数:
a -> 数组
d -> 旋转次数

输入示例:

a = [1,2,3,4,5]
d = 4

预期输出:

[5 1 2 3 4]

我的代码的输出:

[2 3 4 5 1]

似乎它只在j = 0i = 04)时执行循环

如何重写它以获得预期的输出?

function rotLeft(a, d) {
    // Write your code here
    var n = a.length
    var temp = 0
    var i = 0
    var j = 0
    for (j; j < d; j++) {
        for (i; i < n; i++) {
            if (i === 0) {
                temp = a[i];
            }
            a[i] = a[i + 1]
        }
        a[n - 1] = temp
    }

    return a
}

【问题讨论】:

  • 您要返回一个新数组,还是返回具有更新索引的同一个数组?
  • 只想在 d 次旋转后返回 'a'
  • array.unshift(array.pop()) 不会在没有循环的情况下做到这一点吗?

标签: javascript arrays loops


【解决方案1】:

您可以使用Array#splice 删除所有将要移动的元素,然后使用另一个Array#splice 将它们全部添加到末尾

/**
 * @param {Array<string>} list
 * @param {number} rotationCount
 * @returns 
 */
function rotLeft(list, rotationCount) {
    rotationCount = (rotationCount % list.length) | 0; // ignore extra rotations and floor number
    if (rotationCount < 0) rotationCount += list.length; // convert right to negative left
    var removedParts = list.splice(0, rotationCount); // cut the first `rotationCount` elements
    list.splice.apply(list, [list.length, 0].concat(removedParts)); // add the removed elements to the bottom
    // list.splice(list.length, 0, ...removedParts); // or this for es6
    return list;
}

console.log(rotLeft([1,2,3,4,5], 4));

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多