[LeetCode] Rotate Array
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).
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步