全栈开发知识库

6.轮转数组

题目

给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。

示例 1:

  • 输入: nums = [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:

  • 输入:nums = [-1,-100,3,99], k = 2
  • 输出:[3,99,-1,-100]

解释:

  • 向右轮转 1 步: [99,-1,-100,3]
  • 向右轮转 2 步: [3,99,-1,-100]

思路

双层循环

外层循环k此,不断把最后一位移到第一位,然后内层循环每个元素后移一位

class Solution {
    fun rotate(nums: IntArray, k: Int): Unit {
        for (i in 0..<k) {
            val temp = nums[nums.size - 1]
            for (j in nums.size - 1 downTo   1) {
                nums[j] = nums[j - 1]
            }
            nums[0] = temp
        }
    }
}
反转法
  • k=3 [1, 2, 3, 4, 5, 6, 7]
  • 反转整个数组 [7, 6, 5, 4, 3, 2, 1]
  • 反转前k个元素 [5, 6, 7, 4, 3, 2, 1]
  • 反转后n - k个 [5, 6, 7, 1, 2, 3, 4]

注意:这里k可能超过数组的长度,所以要用 k %= n保证超过一轮的问题

# 注:请勿使用切片,会产生额外空间
class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        def reverse(i: int, j: int) -> None:
            while i < j:
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
                j -= 1

        n = len(nums)
        k %= n  # 轮转 k 次等于轮转 k % n 次
        reverse(0, n - 1)
        reverse(0, k - 1)
        reverse(k, n - 1)
class Solution {
    fun rotate(nums: IntArray, k: Int): Unit {
        val realK = k % nums.size

        rotate(nums, 0, nums.lastIndex)
        rotate(nums, 0, realK - 1)
        rotate(nums, realK, nums.lastIndex)
    }

    fun rotate(nums: IntArray, start: Int, end: Int) {
        var startIndex = start
        var endIndex = end
        while (startIndex < endIndex) {
            val temp = nums[startIndex]
            nums[startIndex] = nums[endIndex]
            nums[endIndex] = temp

            startIndex ++
            endIndex --
        }
    }
}

  • 邮箱 :charon.chui@gmail.com
  • Good Luck!