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 + 1 处依次循环右移k次,效率底,代码简单。
第二种
重新开辟一个新数组,缺点是需要n个额外空间
第三种
开一条链,利用链表翻转,耗费空间
第四种
1、将0,n - k - 1 和n - k ,n - 1分别翻转
2、将0,n - 1翻转
public class Solution { public void rotate(int[] nums, int k) { k = k % nums.length;//旋转nums.length没有意义 if(k <= 0){//参数不合适 return ; } int n = nums.length; reverse(nums, 0, n-k-1); reverse(nums, n-k, nums.length-1); reverse(nums, 0, nums.length-1); } private void reverse(int[] nums, int start, int end){ while(start<end){ int tmp=nums[start]; nums[start]=nums[end]; nums[end]=tmp; start++; end--; } } }
原文地址:http://blog.csdn.net/havedream_one/article/details/44300397