[Algorithm] Rotate the array [LeetCode]

1. Topic

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

Two, example

示例 1:

输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1: [7,1,2,3,4,5,6]
向右旋转 2: [6,7,1,2,3,4,5]
向右旋转 3: [5,6,7,1,2,3,4]
示例 2:

输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释: 
向右旋转 1: [99,-1,-100,3]
向右旋转 2: [3,99,-1,-100]

Three, problem solution

Idea: This question talks about rotation, then one idea that comes to mind is to take the modulus and realize the cycle

设:k=2、n=7
0+2%7=2
1+2%7=3
2+2%7=4
3+2%7=5
4+2%7=6
5+2%7=0
6+2%7=1
 
class Solution {
    
    
    public void rotate(int[] nums, int k) {
    
    
       int[] save = new int[nums.length];
         for(int i=0;i<nums.length;i++){
    
    
             save[i]=nums[i];
         }
        for (int i = 0; i < nums.length; i++) {
    
    
            nums[(i + k) % nums.length] = save[i];
        }
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43073558/article/details/108868508