LeetCode OJ 189. Rotate Array

Posted Black_Knight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 189. 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.

[show hint]

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

Related problem: Reverse Words in a String II

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

Subscribe to see which companies asked this question

【思路一】

这个题目的意思是把数组尾部的n = (K%nums.length)个元素移动到数组的前面。一个最简单的想法就是把后面n个元素依次往前移动即可。代码如下:

 1 public class Solution {
 2     public void rotate(int[] nums, int k) {
 3         if(nums==null || nums.length <= 0) return;
 4         int n = k % nums.length;
 5         
 6         for(int i = 0; i < n; i++){
 7             for(int j = nums.length - n + i; j > i; j--){
 8                 int temp = nums[j-1];
 9                 nums[j-1] = nums[j];
10                 nums[j] = temp;
11             }
12         }
13     }
14 }

这样做空间复杂度为O(1),但是时间复杂度较高,如何改进呢?

【思路二】

例如:[1,2,3,4,5,6,7] k = 3

先将5以前的数据翻转得到的数组是[4,3,2,1,5,6,7]

再将5及以后的数据翻转得到的数组是[4,3,2,1,7,6,5]

再将整个数组翻转即得到[5,6,7,1,2,3,4]

代码如下:

 1 public class Solution {
 2     public void rotate(int[] nums, int k) {
 3         if(nums==null || nums.length <= 0 || k%nums.length==0) return;
 4         int length = nums.length;
 5         k = k%length;
 6         
 7         reversal(nums, 0, length - k - 1);
 8         reversal(nums, length -k, length - 1);
 9         reversal(nums, 0, length - 1);
10     }
11     public void reversal(int[] nums, int i, int j){
12         int t = 0;
13         while(i < j  && i >= 0){
14             t = nums[i];
15             nums[i] = nums[j];
16             nums[j] = t;
17             i++;
18             j--;
19             
20         }
21     }
22 }

 

以上是关于LeetCode OJ 189. Rotate Array的主要内容,如果未能解决你的问题,请参考以下文章

Leet Code OJ 189. Rotate Array [Difficulty: Easy]

leetcode 189. Rotate Array

LeetCode 189 Rotate Array(旋转数组)

LeetCode189. Rotate Array

LeetCode 189. Rotate Array

leetcode 189. Rotate Array