【问题标题】:Adding indexes of a list to a new list将列表的索引添加到新列表
【发布时间】:2015-12-12 12:42:57
【问题描述】:

给定一个长度为 3 的整数数组,返回一个元素“向左旋转”的数组,因此 {1, 2, 3} 产生 {2, 3, 1}。

我的第一次尝试(我在 python 中很容易做到这一点,所以我有同样的想法)。

public int[] rotateLeft3(int[] nums) {
      return [nums[1:] + nums[0]];
}

但正如你所料,我得到了一个错误,所以我立即写了这个。

public int[] rotateLeft3(int[] nums) {
    int[] answer = new int[3];
    answer[0] = nums[1];
    answer[1] = nums[2];
    answer[2] = nums[0];
    return answer;
}

我觉得这可能是回答问题最低效的方法,但我这样做只是因为它说长度为 3。我之前的代码适用于所有大小的 python。所以我想知道我以前的代码如何用java编写?

【问题讨论】:

  • 编写一个循环遍历元素并移动它们。向我们展示您编写的循环,我们将帮助您。

标签: java list indexing addition


【解决方案1】:

与收藏: Java - Rotating array

使用整数 nums[];

如果没有,请迭代并将您的 int[] 转换为 Integer[]

或使用http://commons.apache.org/lang/

Integer[] array2= ArrayUtils.toObject(nums);

Collections.rotate(Arrays.asList(nums), -1);

转换为数组:.toArray();

【讨论】:

    【解决方案2】:

    也许……

    public int[] rotateLeft(int size, int[] array) {
      int temp = int[size-1]; // We're just gonna save the las value.
      for (int i = size-1; i == 0; i--) {
        array[i] = array[i-1]; // We move them all 1 to the left.
      }
      array[0] = temp; // This is why we saved the las value.
    
      return array;
    

    希望对你有所帮助!

    【讨论】:

      【解决方案3】:

      您可以使用System.arraycopy 轻松做到这一点:

      int[] arr = { 1, 2, 3};
      int[] rotated = new int[arr.length];
      System.arraycopy(arr, 1, rotated, 0, arr.length - 1);
      rotated[arr.length-1] = arr[0];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-06
        • 1970-01-01
        • 2015-05-10
        • 2021-09-25
        • 2012-12-23
        • 1970-01-01
        相关资源
        最近更新 更多