LeetCode 189 Rotate Array (rotating Array)
Translation
Rotate an array with n elements to the right in K steps. For example, given n = 7 and k = 3, the array [, 7] is rotated to [, 4]. Annotation: Try multiple solutions as much as possible. There are at least three different solutions here.
Original
Rotate an array of n elements to the right by k steps.For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].Note:Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Analysis
Method 1
The first method I think of is to set another vector, add the elements one by one, and assign the vector to nums. You can add k elements on the right and n-k elements on the left.
The Code is as follows:
void rotate(vector
&nums, int k) { if (nums.size() == 1) return; if (k > nums.size()) k %= nums.size(); vector
newNums; for (int i = nums.size() - k; i < nums.size(); ++i) newNums.push_back(nums[i]); for (int i = 0; i < nums.size() - k; ++i) newNums.push_back(nums[i]); nums = newNums;}Runtime: 28 ms
Timeout Method
There is another simplest method, but it timed out ......
void rotate(vector
&nums, int k) { if (nums.size() <= 1) return; if (k > nums.size()) k %= nums.size(); while (k > 0) { int temp = nums[nums.size() - 1]; for (int i = nums.size() -1; i >0; --i) { nums[i] = nums[i - 1]; } nums[0] = temp; k--; }}Time Limit Exceeded
Method 2
The method above does not work. Continue to improve the first method. Cut the vector into the left and right sides.
void rotate(vector
&nums, int k) { if (nums.size() <= 1) return; if (k > nums.size()) k %= nums.size(); vector
extra(nums.begin(), nums.begin() + nums.size() - k); nums.erase(nums.begin(), nums.begin() + nums.size() - k); nums.insert(nums.end(), extra.begin(), extra.end());}Runtime: 28 ms
Method 2 Improvement
How about reversing the order?
void rotate(vector
&nums, int k) { if (nums.size() <= 1) return; if (k > nums.size()) k %= nums.size(); vector
extra(nums.end() - k, nums.end()); nums.erase(nums.end() - k, nums.end()); nums.insert(nums.begin(), extra.begin(), extra.end());}Runtime: 24 ms
It takes four seconds to complete.
Method 3
Another method is to use the rotate () function provided by STL ......
void rotate(vector
& nums, int k) { int len = nums.size(); if (len > 1) { k %= len; std::rotate(nums.begin(), nums.end() - k, nums.end()); }}