Rotate array java

Given an array, move the elements in the array k positions to the right, where k is a non-negative number.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Rotate to the right 1 step: [7,1 ,2,3,4,5,6]
Rotate right 2 steps: [6,7,1,2,3,4,5]
Rotate right 3 steps: [5,6,7,1,2,3 ,4]
Example 2:

Input: [-1, -100,3,99] and k = 2
Output: [3,99, -1, -100]
Explanation:
rotation to the right Step 1: [99, -1, -100,3]
to Rotate right 2 steps: [3,99,-1,-100]
Description:

Think of as many solutions as possible. There are at least three different ways to solve this problem.
It is required to use an in-place algorithm with a space complexity of O(1).

Source: LeetCode
Link: https://leetcode-cn.com/problems/rotate-array
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Idea: Space O(1) I did not expect an O(k%len), save the array of the first k%len bits, traverse it once, and get the answer, post an official space O(1)
ps: Flip twice is equal to no flip.

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

Guess you like

Origin blog.csdn.net/weixin_43824233/article/details/112355984