leetcode初级算法2.旋转数组

leecode初级算法2.旋转数组

仅为个人刷题记录,不提供解题思路

题解与收获

我自己的解法:

public static void rotate(int[] nums, int k) {
        int move = k % nums.length;
        Stack<Integer> stack = new Stack<>();
        if(move == 0){
            return;
        }
        else {
            for(int i = nums.length - move - 1; i >= 0; i--){
                stack.push(nums[i]);
            }
            for(int j = nums.length - 1; j>= nums.length - move; j--){
                stack.push(nums[j]);
            }
        }
        for(int i = 0; i < nums.length; i++){
            nums[i] = stack.pop();
        }
    }

官方题解:

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 += 1;
            end -= 1;
        }
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,职场和发展)