[leetcode] 189. Rotate Array 解题报告

The basic idea is that, for example, nums = [1,2,3,4,5,6,7] and k = 3, first we reverse [1,2,3,4,5,6,7], it becomes[7,6,5,4,3,2,1]; then we reverse[7,6,5], it becomes[5,6,7], finally we reverse the array as a whole, it becomes[4,3,2,1] ---> [1,2,3,4],then end.

另外,对k>nums.length的情况进行出来

public void rotate(int[] nums, int k) {
        k %= nums.length;
        if (nums==null || nums.length==0 || nums.length==1){
            return;
        }
        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-10-31 10:29  pulusite  阅读(91)  评论(0编辑  收藏  举报