Rotate Array Total Accepted: 12759 Total Submissions: 73112 My Submissions Question Solution
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.
題意:循環數組,n代表數組的長度,k代表向右移動的次數。
解法一:
class Solution {
public:
void rotate(int nums[], int n, int k) {
if(n==0)return;
k=k%n;//當k大於n的時候,n次循環會回到初始位置,因此,可以省略若干次
if (k == 0) return;
int *s=new int[k];//為了一步到位的展開移動,申請k個額外空間用於保存被移出去的元素
for(int i=0;i=0;--j)
nums[j+k]=nums[j];//移動
for(int i=0;i
需要額外空間O(k%n)
33 / 33 test cases passed.
Status: Accepted
Runtime: 29 ms
解法二(網絡獲取):
三次翻轉法,第一次翻轉前n-k個,第二次翻轉後k個,第三次翻轉全部。
class Solution {
public:
void rotate(int nums[], int n, int k) {
if(n==0)return ;
k=k%n;
if(k==0)return ;
reverse(nums,n-k,n-1);
reverse(nums,0,n-k-1);
reverse(nums,0,n-1);
}
void reverse(int nums[],int i,int j)
{
for(;i
33 / 33 test cases passed.
Status: Accepted
Runtime: 26 ms