Leetcode 189) Rotate Array

image

class Solution {
    public void rotate(int[] nums, int k) {
        if(nums.length==1){
            return;
        }
        k=k%nums.length;
        int[] tmp = new int[k];
        for(int i=nums.length-k;i<nums.length;i++){
            tmp[i-nums.length+k]=nums[i];
        }
        for(int i =nums.length-k-1;i>=0;i--){
            nums[i+k]=nums[i];
        }
        for(int i=0;i<k;i++){
            nums[i]=tmp[i];
        }
    }
}

다른 답안

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 left, int right) {
        while (left < right) {
            swap(nums, left++, right--);
        }
    }
    
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2