LeetCode-189. Rotate Array

网友投稿 252 2022-08-29

LeetCode-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]​​

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]

题解:

class Solution {public: void rotate(vector& nums, int k) { int n = nums.size(); if (n <= 1) { return; } k %= n; reverse(nums.begin(), nums.end()); reverse(nums.begin(), nums.begin() + k); reverse(nums.begin() + k, nums.end()); }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:为什么购物中心最苦逼的是市场营销人?(为什么喜欢购物中心)
下一篇:LeetCode-203. Remove Linked List Elements
相关文章

 发表评论

暂时没有评论,来抢沙发吧~