LeetCode & Q189-Rotate Array-Easy

Array

Description:

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].

刷题还是习惯早上刷,现在脑子不灵光了,哎...

这题我想的很复杂,可以说和算法不沾边,看了Discuss照着写了一遍。

public class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length-1);
        reverse(nums, 0, k-1);
        reverse(nums, k, nums.length-1);
    }
    
    public void reverse(int[]nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}
posted @ 2017-07-18 17:34  6002  阅读(79)  评论(0编辑  收藏  举报