189. Rotate Array
189.1 题目描述:
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].
189.2 解题思路:
首先,本题中如果k比数组的大小还要大,直接k%数组大小。
思路一:开辟新的内存,将后面k个元素先存起来。然后将原数组中从第一个到第n-k个,都往后移动k位。最后再将先前保存的k位放在原数组前面。
思路二:利用反转。首先反转整个数组,然后反转前k个数组,反转后n-k个。比如说1234567,k=3,则第一次,7654321,第二次,5674321,第三次,5671234。
思路三:利用vector的push和erase函数(Python中list有类似的功能函数)。遍历前n-k个,首先把nums[0]push入数组,然后再把此时的nums[0]erase掉。
189.3 C++代码:
1、思路一代码(19ms):
class Solution133 {
public:
void rotate(vector<int>& nums, int k) {
if ( k==0 )
return;
if (k > nums.size())
k = k % nums.size();
vector<int>temp;
for (int i = nums.size() - k; i < nums.size(); i++)
temp.push_back(nums[i]);
for (int j = nums.size() - 1; j >= k; j--)
nums[j] = nums[j - k];
for (int i = 0; i < k;i++)
nums[i] = temp[i];
}
};
2、思路二代码(19ms)
class Solution133_1 {
public:
void myreverse(vector<int>& nums, int i, int j)
{
while (i<j)
{
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
i++;
j--;
}
}
void rotate(vector<int>& nums, int k) {
if (k == 0)
return;
if (k > nums.size())
k = k % nums.size();
myreverse(nums, 0, nums.size() - 1);
myreverse(nums, 0, k - 1);
myreverse(nums, k, nums.size() - 1);
}
};
3、思路三代码(49ms)
class Solution133_2 {
public:
void rotate(vector<int>& nums, int k) {
if (k == 0)
return;
if (k > nums.size())
k = k % nums.size();
for (int i = 0; i < nums.size()-k; i++)
{
nums.push_back(nums[0]);
nums.erase(nums.begin());
}
}
};
189.4 Python代码:
1、思路一代码(108ms)
class Solution1(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k=k%len(nums)
temp=[]
n=len(nums)
for i in range(n-k,n):
temp.append(nums[i])
j=n-1
while j>=k:
nums[j]=nums[j-k]
j-=1
for i in range(0,k):
nums[i]=temp[i]
3、思路三代码(119ms)
class Solution2(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k=k%len(nums)
n=len(nums)
for i in range(n-k):
nums.append(nums[0])
nums.pop(0)