189. Rotate Array
Tags:
Medium
Skills:
Array
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu xoay mảng nums sang phải k bước, thực hiện in-place. Có nhiều cách giải nhưng tối ưu vè TC, SC là dùng kỹ thuật đảo ngược (reverse)
Approach
k bước, phần tử cuối cùng sẽ lên đầu, các phần tử khác dịch sang phảik lớn hơn độ dài mảng, ta lấy k = k % nums.length k phần tử đầuSolution
1/**
2 Do not return anything, modify nums in-place instead.
3 */
4function rotate(nums: number[], k: number): void {
5 let n = nums.length;
6 k = k % n;
7 if (k === 0) return;
8 function reverse(start: number, end: number): void {
9 while (start < end) {
10 [nums[start], nums[end]] = [nums[end], nums[start]]
11 start++
12 end--
13 }
14 }
15
16 reverse(0, n - 1);
17 reverse(0, k - 1)
18 reverse(k, n - 1)
19};