题意:给出一个包含n个元素的数组a和包含m个元素的数组p,其中p中元素的和等于n,p中的每个元素表示将数组a的对应的个数当作一个集合,问将数组a反转后是怎样的
例如 a=[1,2, 3, 4, 5, 6], p=[2, 1, 3],反转后变为[4,5,6,3,1,2]
思路:数组旋转算法
代码如下:
#include <iostream>
using namespace std;
class RotateStrategy
{
public:
virtual void rotateArr(int *a, int n, int k) = 0;
};
class GcdRotate : public RotateStrategy
{
public:
void rotateArr(int *a, int n, int k)
{
int gcd = Gcd(n - k, n);
int x = n - k, y = k;
for (int i = 0; i < gcd; i++)
{
int cur = a[i];
int p = i;
if (x <= y)
{
for (int j = 0; j < y / gcd; j++)
{
if (p > i + y)
{
a[p] = a[p - y];
p = p - y;
}
a[p] = a[p + x];
p = p + x;
}
}
else
{
for (int j = 0; j < x / gcd - 1; j++)
{
if (p + x < n)
{
a[p] = a[p + x];
p = p + x;
}
a[p] = a[p - y];
p = p - y;
}
}
a[p] = cur;
}
}
private:
int Gcd(int n, int m)
{
if (m == 0) return n;
else
{
return Gcd(m, n % m);
}
}
};
class Solution
{
public:
Solution(RotateStrategy* rotateStategy)
{
this->rotateStrategy = rotateStategy;
}
void reverseArray(int *a, int n, int *p, int m)
{
int shift = 0;
for (int i = m - 1; i >= 0; i--)
{
rotateStrategy->rotateArr(a + shift, n - shift, p[i]);
shift += p[i];
}
}
private:
RotateStrategy* rotateStrategy;
};
void printArray(int *a, int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
int main()
{
Solution solution(new GcdRotate());
int a[] = {1, 2, 3, 4, 5, 6, 7, 8};
int p[] = {1, 4, 3};
cout << "before process:";
printArray(a, sizeof(a)/ sizeof(int));
solution.reverseArray(a, sizeof(a) / sizeof(int), p, sizeof(p) / sizeof(int));
cout << "after process:";
printArray(a, sizeof(a) / sizeof(int));
return 0;
}