#include<iostream> #include<vector> using namespace std; class Solution { public: void rotate(vector<int>& nums, int k) { //可参考STL源码剖析rotate()算法 k = k%nums.size(); vector<int>::iterator first = nums.begin(); vector<int>::iterator last = nums.end(); vector<int>::iterator middle = last - k; //边界条件 if (first == middle || middle == last) return; vector<int>::iterator i = middle; while (true){ //前后段一一交换 int temp = *i; *i = *first; *first = temp; ++first; ++i; //判断前段先结束还是后段先结束 if (first == middle){ if (i == last)//同时结束,整个就结束 return; middle = i; } else if (i == last) i = middle; } } }; int main(){ vector<int> vec = { 1, 2 }; Solution solution; solution.rotate(vec, 3); for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; cout << endl; system("pause"); return 0; }