189. Rotate Array

Total Accepted: 61150
Total Submissions: 300206
Difficulty: Easy

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.

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
   public void reverse(int[] nums,int l,int r){
        while(l<r){
            int temp=nums[l];
            nums[l++]=nums[--r];
            nums[r]=temp;
        }
    }
    public void rotate(int[] nums, int k) {
        int n=nums.length;
        k=k%n;
        reverse(nums, 0  ,n-k);
        reverse(nums, n-k,n  );
        reverse(nums, 0  ,n  );
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。