189. Rotate Array
Posted dmndxld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了189. Rotate Array相关的知识,希望对你有一定的参考价值。
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]
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?
My idea:pop insert 投机了
class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ l=len(nums) k=k%l for i in range(k): a=nums.pop() nums.insert(0,a)
执行用时 : 184 ms, 在Rotate Array的Python3提交中击败了20.09% 的用户
内存消耗 : 12.9 MB, 在Rotate Array的Python3提交中击败了99.73% 的用户
学习一下别人的思路,四种方法很详细:
import java.util.Arrays; class Solution { /** * 双重循环 * 时间复杂度:O(kn) * 空间复杂度:O(1) */ public void rotate_1(int[] nums, int k) { int n = nums.length; k %= n; for (int i = 0; i < k; i++) { int temp = nums[n - 1]; for (int j = n - 1; j > 0; j--) { nums[j] = nums[j - 1]; } nums[0] = temp; } } /** * 翻转 * 时间复杂度:O(n) * 空间复杂度:O(1) */ public void rotate_2(int[] nums, int k) { int n = nums.length; k %= n; reverse(nums, 0, n - 1); reverse(nums, 0, k - 1); reverse(nums, k, n - 1); } private void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start++] = nums[end]; nums[end--] = temp; } } /** * 循环交换 * 时间复杂度:O(n) * 空间复杂度:O(1) */ public void rotate_3(int[] nums, int k) { int n = nums.length; k %= n; // 第一次交换完毕后,前 k 位数字位置正确,后 n-k 位数字中最后 k 位数字顺序错误,继续交换 for (int start = 0; start < nums.length && k != 0; n -= k, start += k, k %= n) { for (int i = 0; i < k; i++) { swap(nums, start + i, nums.length - k + i); } } } /** * 递归交换 * 时间复杂度:O(n) * 空间复杂度:O(n/k) */ public void rotate(int[] nums, int k) { // 原理同上 recursiveSwap(nums, k, 0, nums.length); } private void recursiveSwap(int[] nums, int k, int start, int length) { k %= length; if (k != 0) { for (int i = 0; i < k; i++) { swap(nums, start + i, nums.length - k + i); } recursiveSwap(nums, k, start + k, length - k); } } private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
以上是关于189. Rotate Array的主要内容,如果未能解决你的问题,请参考以下文章