LeetCode189. Rotate Array
Posted 月盡天明
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode189. Rotate Array相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/rotate-array/
Description
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
题目要求空间复杂度为O(1),没有要求时间复杂度。
Solution 1
将数组依次向后移动,一共移动 k 次。
public void rotate(int[] nums, int k)
for(int i = 0; i < k; i++)
int temp = nums[nums.length - 1];
for(int j = nums.length - 1; j > 0; j--)
nums[j] = nums[j - 1];
nums[0] = temp;
Solution 2
/**
* 将后面的往前移动
* 74ms
*
* @param nums
* @param k
*/
public void rotate1(int[] nums, int k)
if (nums == null || nums.length == 0 || nums.length == 1)
return;
if (k > nums.length)
k = k % nums.length;
for (int i = 0; i < k; i++)
int temp = nums[nums.length - k + i];
for (int j = nums.length - k + i; j > i; j--)
nums[j] = nums[j - 1];
nums[i] = temp;
Solution 3
/**
* 数组拷贝
* 1ms
*
* @param nums
* @param k
*/
public void rotate2(int[] nums, int k)
if (nums == null || nums.length == 0 || nums.length == 1)
return;
if (k > nums.length)
k = k % nums.length;
int[] result = new int[nums.length];
for (int i = 0; i < k; i++)
result[i] = nums[nums.length - k + i];
for (int i = k; i < nums.length; i++)
result[i] = nums[i - k];
System.arraycopy(result, 0, nums, 0, nums.length);
Solution 4
可以通过递归方式来实现。将数组分为前后两个分别做翻转,然后整体再翻转。
/**
* 递归方式,左右两个数组分别倒置,然后整体再倒置
* 1ms
*
* @param nums
* @param k
*/
public void rotate3(int[] nums, int k)
if (nums == null || nums.length == 0 || nums.length == 1)
return;
if (k > nums.length)
k = k % nums.length;
reverse(nums, 0, nums.length - k - 1);
reverse(nums, nums.length - k, nums.length - 1);
reverse(nums, 0, nums.length - 1);
public void reverse(int[] arr, int left, int right)
if (arr == null || arr.length == 0 || arr.length == 1)
return;
int temp = 0;
while (left < right)
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
以上是关于LeetCode189. Rotate Array的主要内容,如果未能解决你的问题,请参考以下文章