LeetCode 189 Rotate Array

旋转数组 k 布

标签:数组类问题LeetCode发布于:编辑于:浏览量:1316

概述

https://leetcode.com/problems/rotate-array/

这道题好像剑指 Offer 上有哦。

暴力法

直接暴力遍历。

原地旋转

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        helper(nums, 0, nums.size()-1);
        k %= nums.size();
        helper(nums, 0, k-1);
        helper(nums, k, nums.size()-1);
    }
    
    void helper(vector<int>& nums, int l, int r) {
        while (l < r) {
            swap(nums[l++], nums[r--]);
        }
    }
};