#include#include using namespace std;class Solution {public: void rotate(vector & nums, int k) { //可参考STL源码剖析rotate()算法 k = k%nums.size(); vector ::iterator first = nums.begin(); vector ::iterator last = nums.end(); vector ::iterator middle = last - k; //边界条件 if (first == middle || middle == last) return; vector ::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 vec = { 1, 2 }; Solution solution; solution.rotate(vec, 3); for (vector ::iterator it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; cout << endl; system("pause"); return 0;}