189. Rotate Array

来源:互联网 发布:浴室柜推荐 知乎 编辑:程序博客网 时间:2024/05/29 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]

Hint:
Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II

问题:向右旋转数组k次,如{1,2,3,4,5,6,7} k=3 则得到数组{5,6,7,1,2,3,4}

思想:(1)最简单的利用两层循环,每一循环,所有元素和最后的元素交换

public void rotate3(int[] nums, int k) {//双层循环int pre,temp;for(int j=0;j<k;j++){pre=nums[nums.length-1];//System.out.println("最后元素:"+pre);for(int i=0;i<nums.length-1;i++){temp=nums[i];nums[i]=pre;pre=temp;}nums[nums.length-1]=pre;}printArray(nums);}
(2)假设k=2,i=0则i右移的(i+k)%len步,在开辟一个数组来保存正确位置

public void rotate(int[] nums, int k) {//开辟新空间int[] a=new int[nums.length];for(int i=0;i<nums.length;i++){a[(i+k)%nums.length]=nums[i];}for(int i=0;i<nums.length;i++){nums[i]=a[i];}printArray(nums);}

(3)方法1简单但是时间复杂度是n^2,方法2虽然是线性的但其占用了新空间,在此提出方法3

例子:1移动到4处, 4移动到7处,7处移动到1处,2移动到5处......

public void rotate(int[] nums, int k) {//开辟新空间k=k%nums.length;int count=0;for(int i=0;count<nums.length;i++){//i是初次移动的位置,移回原位后新的移动元素int current=i;//当前移动的元素的下标int pre=nums[i];//当前移动的元素do{int next=(current+k)%nums.length;//移动到的位置int temp=nums[next];nums[next]=pre;pre=temp;current=next;count++;//count表示所有的元素都移动完}while(i!=current);//当前移动的位置不是刚刚选定的i,即没有出现1要移动4处 4移动到7处 7移动到1处}//printArray(nums);}




0 0
原创粉丝点击