c++ - 循环旋转codility c++解决方案

标签 c++ vector solution

我正在尝试解决这个问题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/

相关文章:

c++ - 配置:错误:C++ 预处理器 "/lib/cpp"完整性检查失败

C++:允许访问 protected 类成员而不是私有(private)成员

c++ - 由于 C++ 中的段错误而导致应用程序崩溃的方法

c++ - 将 const* 存储在 const vector 中

xml - 在构建解决方案时,如何让 MSBuild 任务生成 XML 文档?

c++ - Qt QFrame StyleSheet 在 MainWindow 中不工作

c++ - VC++中如何获取空闲端口号列表?

c++ - 如何使用std::vector <unique_ptr <T >>作为默认参数

visual-studio - 如何在 Visual Studio 2008 中对项目进行排序?

visual-studio-2008 - VS2008 中的解决方案文件夹不按字母顺序排列