ðŸ¥ˆ

Rotate Array

Created
2022/01/30 14:44
ë¬¸ì œ ë²ˆí˜¸
189
ì¹´í…Œê³ ë¦¬
Array
Math
Two Pointers

Code

 .css-15tnwsa{max-width:100%;width:100%;white-space:pre-wrap;word-break:break-word;padding:7px 9px;background-color:transparent;font-size:14px;line-height:20px;min-height:1em;}.css-15tnwsa:empty::after{content:" ";}ì œì¶œ ë‚ ì§œ ì‹œê°„ ë©”ëª¨ë¦¬ 2022/01/30 24 ms 8 MB
// 189. Rotate Array // // https://leetcode.com/problems/rotate-array/ // rotate function rotates the nums slice by iterating the number with k. // Time complexity O(n) & non-additional memory is the way with reserve the slice several times. // For about k, only k mod the length of the nums slice is required to rotate the slice. // Reverse index 0 to len(nums) - 1. // Reverse index 0 to k - 1. // Reverse index k to len(nums) - 1. func rotate(nums []int, k int) { k %= len(nums) reverse := func(nums []int, start, end int) { for start < end { nums[start], nums[end] = nums[end], nums[start] start++ end-- } } reverse(nums, 0, len(nums)-1) reverse(nums, 0, k-1) reverse(nums, k, len(nums)-1) }
Go