我正在尝试解决这个问题in Codility ...
这是代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> solution(vector<int> &A, int k);
vector<int> A;
A.push_back(3);
A.push_back(5);
A.push_back(7);
A.push_back(9);
A.push_back(2);
int k;
rotate(A.rbegin(),A.rbegin()+k, A.rend());
虽然我的编译器编译和运行没有问题,但 codility 向我显示“错误:'A' 没有命名类型”。 这是我的编译器用来检查它的代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> myVector;
myVector.push_back(3);
myVector.push_back(5);
myVector.push_back(7);
myVector.push_back(9);
myVector.push_back(2);
for(unsigned i=0;i<myVector.size();i++)
{
cout<<myVector[i]<<" ";
}
cout<<endl;
int k;
cout<<"Insert the times of right rotation:";
cin>>k;
rotate(myVector.rbegin(),myVector.rbegin()+k, myVector.rend());
for(unsigned i=0;i<myVector.size();i++)
{
cout<<myVector[i]<<" ";
}
}
编译器输出:
func.cpp:9:3: error: 'A' does not name a type
A.push_back(3);
^
func.cpp:10:3: error: 'A' does not name a type
A.push_back(5);
^
func.cpp:11:3: error: 'A' does not name a type
A.push_back(7);
^
func.cpp:12:3: error: 'A' does not name a type
A.push_back(9);
^
func.cpp:13:3: error: 'A' does not name a type
A.push_back(2);
^
func.cpp:16:9: error: expected constructor, destructor, or type conversion before '(' token
rotate(A.rbegin(),A.rbegin()+k, A.rend());
^
func.cpp:18:1: error: expected declaration before '}' token
}
^
Detected some errors.
最佳答案
如果您不想使用 <algorithm>
中的旋转功能.
Codility给出的结果:
Programming : C++
Task Score: 100%
Correctness: 100%
Performance: Not assesed
解决方法:
vector<int> solution(vector<int> &A, int K)
{
vector <int> shift;
if (A.empty()) // check for empty array
return {};
if (K > A.size()) //if K bigger then size of array
K = K%A.size();
if (K<A.size())
K=A.size()-K; //normalize K to the position to start the shifted array
if (K == A.size()) //if K= size of array, avoid any computation.
return A;
for (unsigned int i=K; i<A.size(); i++)
{
shift.push_back(A[i]);
}
for (unsigned int i=0; i<K; i++)
{
shift.push_back(A[i]);
}
return shift;
}
关于c++ - 循环旋转codility c++解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45577106/