题解 | #旋转数组#
旋转数组
https://www.nowcoder.com/practice/e19927a8fd5d477794dac67096862042
直接法
#include <vector> class Solution { public: vector<int> solve(int n, int m, vector<int>& a) { m = m % n; vector<int> res; for (int i = n - m; i < n; i++) { res.push_back(a[i]); } for (int i = 0; i < n - m; i++) { res.push_back(a[i]); } return res; } };
三次翻转
class Solution { public: vector<int> solve(int n, int m, vector<int>& a) { m = m % n; reverse(a.begin(), a.end()); reverse(a.begin(), a.begin()+m); reverse(a.begin()+m, a.end()); return a; } };