BM97. 旋转数组
描述
示例1
输入:
6,2,[1,2,3,4,5,6]
输出:
[5,6,1,2,3,4]
示例2
输入:
4,0,[1,2,3,4]
输出:
[1,2,3,4]
C++ 解法, 执行用时: 2ms, 内存消耗: 324KB, 提交时间: 2021-06-05
class Solution { public: /** * 旋转数组 * @param n int整型 数组长度 * @param m int整型 右移距离 * @param a int整型vector 给定数组 * @return int整型vector */ vector<int> solve(int n, int m, vector<int>& a) { // write code here vector<int>v; m = m%n; for(int i=n-m;i<n;i++) { v.push_back(a[i]); } for(int i=0;i<n-m;i++) { v.push_back(a[i]); } return v; } };
C 解法, 执行用时: 2ms, 内存消耗: 328KB, 提交时间: 2021-02-20
/** * 旋转数组 * @param n int整型 数组长度 * @param m int整型 右移距离 * @param a int整型一维数组 给定数组 * @param aLen int a数组长度 * @return int整型一维数组 * @return int* returnSize 返回数组行数 */ int* solve(int n, int m, int* a, int aLen, int* returnSize ) { *returnSize=aLen; if(n==0||n==1) return a; m= m%n; int p,q; for (int i = 0;i<m;i++) { p = a[n-1]; for(int j = 0;j<n;j++) { q=a[j]; a[j]=p; p = q; } } return a; }
C++ 解法, 执行用时: 2ms, 内存消耗: 328KB, 提交时间: 2020-11-01
class Solution { public: /** * 旋转数组 * @param n int整型 数组长度 * @param m int整型 右移距离 * @param a int整型vector 给定数组 * @return int整型vector */ vector<int> solve(int n, int m, vector<int>& a) { vector<int> d; int finished = 0; int count = a.size(); for (int i=0; i < count; ++i) { if (finished >= count) break; int begin = i; int cur = i; int tmp = a[cur]; int prev = prev_index(cur, m, n); while (begin != prev) { d.push_back(cur); d.push_back(prev); d.push_back(0); finished++; a[cur] = a[prev]; cur = prev; prev = prev_index(cur, m, n); } finished++; d.push_back(cur); d.push_back(tmp); d.push_back(0); a[cur] = tmp; } for (auto& i : a) d.push_back(i); return a; } int prev_index(int i, int len, int count) { i -= len; while (i < 0) { i += count; } return i; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 336KB, 提交时间: 2020-12-21
class Solution { public: /** * 旋转数组 * @param n int整型 数组长度 * @param m int整型 右移距离 * @param a int整型vector 给定数组 * @return int整型vector */ vector<int> solve(int n, int m, vector<int> &a) { // write code here if (!n) return a; if (!m) return a; m %= n; reverse(a.begin(), a.end()); reverse(a.begin(), a.begin() + m); reverse(a.begin() + m , a.end()); return a; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 336KB, 提交时间: 2020-11-23
class Solution { public: /** * 旋转数组 * @param n int整型 数组长度 * @param m int整型 右移距离 * @param a int整型vector 给定数组 * @return int整型vector */ vector<int> solve(int n, int m, vector<int>& a) { // write code here int start = 0; int pos = start; int count = 0; int tmp1 = a[start]; int tmp2 = tmp1; m = m % n; while(true) { tmp1 = a[(pos + m) % n]; a[(pos + m) % n] = tmp2; tmp2= tmp1; pos = (pos + m) % n; count ++; if(count == n) break; if(pos == start) { start = start + 1; pos = start; tmp1 = a[start]; tmp2 = a[start]; } } return a; } };