189. Rotate Array

本文介绍了一种将数组元素向右旋转k步的操作,并提供了两种解决方案。第一种方法通过不断将数组的第一个元素移到末尾来实现旋转,但时间复杂度较高。第二种方法采用三次反转的方式,先反转前n-k个元素,再反转后k个元素,最后反转整个数组,实现了O(n)的时间复杂度。

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.

 

Solution 1: note that line 6 uses k%size. the time complexity of erase is O(n), so the worst total time could be O(n^2)

 1 class Solution {
 2 public:
 3     void rotate(vector<int>& nums, int k) {
 4         int size=nums.size();
 5         int i=0;
 6         while (i<size-k%size){
 7             nums.push_back(nums[0]);
 8             nums.erase(nums.begin());
 9             i++;
10         }
11     }
12 };

Solution 2:reverse the previous n-k nums and then reverse the later k nums. Finally reverse all. O(n)

1 2 3 4 5 6 7 

4321567

4 3 2 1 7 6 5

5 6 7 1 2 3 4

 1 class Solution {
 2 public:
 3     void rotate(vector<int>& nums, int k) {
 4         if (nums.empty() || (k %= nums.size()) == 0) return;
 5         int n = nums.size();
 6         reverse(nums.begin(), nums.begin() + n - k);
 7         reverse(nums.begin() + n - k, nums.end());
 8         reverse(nums.begin(), nums.end());
 9     }
10 };

 

转载于:https://www.cnblogs.com/anghostcici/p/6917120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值