leetcode Rotate Array

来源:互联网 发布:php 表单数据提交 编辑:程序博客网 时间:2024/06/07 02:37

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.

[show hint]

Related problem: Reverse Words in a String II

Credits:

Special thanks to @Freezen for adding this problem and creating all test cases.

虽然是一道easy的题目,但自己想到的解法都出现超时的情况,网上看到一个很好的解法,下面举个例子:

如1 2 3 4 5 6 7 k=3

以5为边界,翻转5之前的数字:4 3 2 1 5 6 7

然后翻转5与5之后的数字:4 3 2 1 7 6 5

翻转整个数组:5 6 7 1 2 3 4 完成。

对此我只能说,数学很神奇。。。

代码:

public void rotate(int[] nums, int k) {   int len=nums.length;    if(k>=len) k%=len;    reverse(nums,0,len-k-1);    reverse(nums,len-k,len-1);    reverse(nums,0,len-1);}public void reverse(int[] a,int i,int j){    int temp;    for(;i<j;i++,j--){        temp=a[i];        a[i]=a[j];        a[j]=temp;    }}

0 0
原创粉丝点击