1.1数组和链表:189. Rotate Array(Leetcode)

来源:互联网 发布:数据库一致性错误修复 编辑:程序博客网 时间:2024/06/14 13:58

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

大意:在长度为n的数组中,将后k位数以固定的相对顺序旋转至数组开头。

解法一:

比较容易想到:复制一个和nums一样的数组,然后利用映射关系i -> (i+k)%n来交换数字。代码如下:

public void rotate(int[] nums, int k) {        int n = nums.length;        int[] newNums = new int[n];        for(int i = 0;i < n;i ++)            newNums[i] = nums[i];        for(int i = 0;i < n;i ++){            nums[(i + k) % n] = newNums[i];        }            }
由于提示中提醒空间复杂度为O(1)而上述代码为O(N),所以我们可以延续上面的思路,用O(1)的空间复杂度来解决问题:下图展示nums元素的变化情况。

1 2 3 4 5 6 7 
1 2 3 1 5 6 7
1 2 3 1 5 6 4
1 2 7 1 5 6 4
1 2 7 1 5 3 4
6 7 1 5 3 4
1 6 7 1 2 3 4
5 6 7 1 2 3 4

代码如下

解法二:

public void rotate(int[] nums, int k) {        if(nums.length == 0 || (k %= nums.length) == 0) return;        int n = nums.length;        int i = 0,start = 0,temp = nums[i],count = 0;        while(count ++ < n){                        int index = (i + k) % n;            int temp2 = nums[index];            nums[index] = temp;            temp = temp2;                        i = index;            if(index == start){                i ++;start++;                temp = nums[i];            }                    }                   }

第一行代码确保k在取余n为0的时候(多表现为k与n相等),可以直接返回,因为此时数组不做任何变化,如果不返回会造成后续代码的数组脚标越界,定义count来确定是否每个元素都发生了变化,定义temp来存储在转换过程中被替换位置的值,因为先后顺序的关系这个值必须先由temp2存储(因为temp需要先将她的值赋给当前位置)之后再由temp2赋给temp,temp应定义在循环外,因为他需要在各次循环中通信。判断index == start是为了防止n能够被k整除时候造成的无限循环。

剩余解法见http://www.cnblogs.com/grandyang/p/4298711.html,因有几个解法尚未理解,在此不做阐述。

原创粉丝点击