给定一个数组,将数组中的元素向右移动 个位置,其中 是非负数。

说明:

  • 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
  • 要求使用空间复杂度为 O(1) 的 原地 算法。

方案1: 额外设置一个数组储存原数组,这是因为原数组的值得保存,不然直接覆盖就没了

public class RotateArray {

    public static void rotate(int[] nums, int k) {
        if(nums.length==0)
            return;
        int move = k%nums.length;
        Integer[] temp = new Integer[nums.length];
        for(int i=0; i<nums.length; i++) {
            temp[i]=nums[i];
        }
        for(int i=0; i<nums.length; i++) {
            if(i+move<nums.length) {
            nums[i+move]=temp[i];
            }
            else {
                nums[i+move-nums.length]=temp[i];
            }
        }
    }
}

看下要移动的位数,然后直接赋值,把temp临时数组中保存好的原数组值直接赋给原数组对应的位

这里注意一下数组越界的问题,index如果大于length就减掉length,其实也是对length取余的操作,保证所有操作不会超出数组上限。

2.(more solutions to be accomplished)

posted on 2019-12-03 19:57  寺川愛美  阅读(203)  评论(1)    收藏  举报