繁体   English   中英

左右移动数组

[英]Move array to left and right

我在 eclipse 中使用 java。 我正在尝试解决两个问题。 我知道如何将数组向右或向左移动一个,并用第一个或第一个用最后一个填充最后一个元素。 我现在正在尝试移动一个数组,例如向右移动三个索引或向左移动三个索引。 有人可以提供帮助吗? 我不想使用模数。

例如,我的数组是{1,2,3,4,5} :如果 x 为负,我将它向左旋转三个索引,所以在这种情况下: x = -3

if (x < 0) {
  for (i = length1 - 2, j = 0; j < (length1 - Math.abs(x)); i++, j++) {
        temp[i] = myArray[j];
  }
  for (i = 0, j = (length1 - Math.abs(x)); j < length1; i++, j++) {
        temp[i] = myArray[j];
  }
}

这不会运行,除非在我的第一个 for 循环中,我有: i = length1 - 2

有没有更通用的方法来做到这一点? 如果我试图将数字旋转 23 个索引怎么办,我将如何 go 这样做?

输入1,2,3,4,5 output 4,5,1,2,3

您可以使用一种非常简单的算法将数组的位置向右或向左移动:

您从一个空数组开始并迭代您的初始数组,跳过 N 个位置然后按顺序填充,将跳过的内容添加到索引中并使用 % 模数来确保到达结束后回到开始

如果要允许负数,还可以添加原始数组以确保始终为正数并再次使用模数绑定移位,因此移位永远不会太大,因为将三个元素的数组移位三次就像不做任何事物

这是一些代码示例:(它实际上是 javascript,以便您可以在这里运行它,但是您明白了这个想法和语法非常相似

 function moveBy(array, num){ num = num % array.length; // bounds the shift let result = new Array(array.length); // inits empty array for (let i = 0; i < array.length; i++) { let mappedIndex = (i + num + array.length) % array.length; result[i] = array[mappedIndex]; // skips num elements and fills everything using % to get back to the begining once reached the end } return result; } let example = [1,2,3,4,5]; console.log(moveBy(example, 1)); console.log(moveBy(example, 3)); console.log(moveBy(example, -2));

public void move(int[] nums, int k) {
    
    k = k % nums.length;
    
    // Reverse the orginal array.
    swap(nums, 0, nums.length - 1);
    
    // Reverse the left portion.
    swap(nums, 0, k - 1);
    
    // Reverse the right portion.
    swap(nums, k, nums.length - 1);
}    

private void swap(int[] nums, int l, int r) {
    while (l <= r) {
        
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
        
        l++;
        r--;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM