1. 程式人生 > >[leetcode]189. Rotate Array

[leetcode]189. Rotate Array

Solution1: 第一反應就是暴力,竟然也過了

class Solution {
    public void rotate(int[] nums, int k) {
        for(int m=0;m<k;m++){
            int temp=nums[nums.length-1];
            for(int i=nums.length-1;i>0;i--){
                nums[i]=nums[i-1];
            }
            nums[0]=temp;
        }
    }
}

Solution 2:3次reverse

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--;
        }
    }
}