LeetCode-06-Rotate Array

Rotate the array 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: Rotate to the right by 1 step: [99,-1,-100, 3] Rotate right 2 steps: [3,99,-1,-100]

Explanation: 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).

  1. Brute force cracking: rotate k times, one element at a time
public static void rotate(int[] array, int k) {
    
    
		int length = array.length;
		int newk = k % length;
		int temp = 0;
		for(int i = 0; i < newk; i++) {
    
    
			temp = array[length - 1];
			for(int j = length - 2; j >= 0; j--) {
    
    
				array[j+1] = array[j];
			}
			array[0] = temp;
		}
	}

Time complexity: O(n*k). Space complexity: O(1).

  1. Use extra array
 public class Solution {
    
    
    public void rotate(int[] nums, int k) {
    
    
        int[] a = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
    
    
            a[(i + k) % nums.length] = nums[i];
        }
        for (int i = 0; i < nums.length; i++) {
    
    
            nums[i] = a[i];
        }
    }
}

Time complexity: O(n). Space complexity: O(n).

Author: LeetCode
link: https: //leetcode-cn.com/problems/rotate-array/solution/xuan-zhuan-shu-zu-by-leetcode/
Source: stay button (LeetCode)

Guess you like

Origin blog.csdn.net/TroyeSivanlp/article/details/108740097