轮转数组
暴力差值法(超时)
class Solution { public: void rotate(vector<int>& nums, int k) { k = k % nums.size(); while(k--) { int tmp = nums[nums.size()-1]; nums.erase(nums.end()-1); nums.insert(nums.begin(),tmp); } } };
转换双向数组
class Solution { public: void rotate(vector<int>& nums, int k) { k = k % nums.size(); deque<int> my_deque(nums.begin(),nums.end()); while(k--) { int tmp = my_deque.back(); my_deque.pop_back(); my_deque.push_front(tmp); } nums.clear(); nums.assign(my_deque.begin(),my_deque.end()); } };
翻转法
class Solution { public: void rotate(vector<int>& nums, int k) { k = k % nums.size(); deque<int> my_deque(nums.begin(),nums.end()); reverse(nums.begin() , nums.end()); reverse(nums.begin(),nums.begin()+k); reverse(nums.begin()+k,nums.end()); } };