[LeetCode] Rotate Array

本文提供了两种在O(1)空间复杂度下实现数组旋转的方法。第一种方法通过三次反转来达到目的,第二种方法利用交换操作实现。文章还提供了一个包含五种解决方案的链接。

This problem, as stated in the problem statement, has a lot of solutions. Since the problem requires us to solve it in O(1) space complexity, I only show some of them in the following.

The first one, also my favorite one, is to apply reverse to nums for three times. You may run some this code on some examples to see how it works.

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

The second one is to use swap, and is translated from the C code in this link.

1 class Solution {
2 public:
3     void rotate(vector<int>& nums, int k) {
4         int start = 0, n = nums.size();
5         for (; k %= n; n -= k, start += k)
6             for (int i = 0; i < k; i++)
7                 swap(nums[start + i], nums[start + n - k + i]);
8     }
9 };

For a more comprehensive summary of other solutions, you may refer to this link (it has 5 solutions).

转载于:https://www.cnblogs.com/jcliBlogger/p/4653377.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值