Rotate Array

2024. 9. 3. 21:18알고리즘/Leetcode

반응형

Solution

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

 

Example

Input: nums = [1,2,3,4,5,6,7], k = 3

Output: [5,6,7,1,2,3,4]

Explanation:

rotate 1 steps to the right: [7,1,2,3,4,5,6]

rotate 2 steps to the right: [6,7,1,2,3,4,5]

rotate 3 steps to the right: [5,6,7,1,2,3,4]

 

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);
    }
    
    private void reverse(int[] nums, int s, int e){
        while(s < e){
            int tmp = nums[s];
            nums[s] = nums[e];
            nums[e] = tmp;
            s++;
            e--;
        }
    }
}

 

Explanation:

  1. First, calculate k %= nums.length to handle cases where k is greater than the array's length.
  2. Reverse the entire array.
  3. Reverse the first k elements (which will move them into their final positions at the end).
  4. Reverse the remaining elements from k to the end of the array, placing them in their correct positions at the start.

In the reverse method, the array (or part of it) is reversed by repeatedly swapping elements at the start (s) and end (e) indices, and moving inward until s is no longer less than e.

반응형

'알고리즘 > Leetcode' 카테고리의 다른 글

Move Zeroes  (2) 2024.09.23
Plus One  (2) 2024.09.20
Intersection of Two Arrays II  (1) 2024.09.12
Single Number  (2) 2024.09.05
Best Time to Buy and Sell Stock II  (0) 2024.08.31