码迷,mamicode.com
首页 > 其他好文 > 详细

Rotate Array

时间:2015-03-16 09:55:48      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:leetcode   rotate array   

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--;  
        }  
    }
}



Rotate Array

标签:leetcode   rotate array   

原文地址:http://blog.csdn.net/havedream_one/article/details/44300397

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!