【LeetCode】16.Array and String — Rotate Array 旋转数组

本文提供了三种不同的算法来解决数组右旋k步的问题,包括使用栈思维的进阶出、利用取余规律重排数组元素以及按步骤执行的直接方法。前两种方法可在LeetCode上通过,而第三种方法因空间消耗过大未能通过。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Example 1:

Input: [1,2,3,4,5,6,7] and 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]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

    题目的解释中已经给的很清楚,在这里提供三种解法,其中第一和第二种算法Accept,第三种由于占用空间过多无法通过,写一下提供参考。
    法一:用栈的思维,先进后出,后出前进,调用C++自带函数,可以很简单的实现算法,该方法Accept。
     1 void rotate(vector<int>&nums, int k)
     2 {
     3     int size = nums.size();
     4     int record;
     5     int counter = k;
     6     while (counter>0)
     7     {
     8         record = nums[size - 1];
     9         nums.pop_back();
    10         nums.insert(nums.begin(), record);
    11         counter--;
    12     }
    13 }


    法二:利用取余规律进行数组数据按要求重排,方法简单,Accept。

    1 void rotate(vector<int>&nums, int k)
    2 {
    3     if (nums.size() == 0 || k <= 0)return;
    4     vector<int> space(nums);
    5     for (int i = 0; i<nums.size(); i++)
    6         nums[(i + k) % nums.size()] = space[i];
    7 }

    法三:严格按照Explanation中的步骤一步步执行,消耗空间多,无法Accept。

     1 void rotate(vector<int>nums, int k) //时间复杂度较高,LeetCode无法通过
     2 {
     3     int size = nums.size();
     4     int record;
     5     int counter = k;
     6     while (counter>0)
     7     {
     8         record = nums[size-1];
     9         for (int j = size - 1; j > 0; --j)
    10         {
    11             nums[j] = nums[j-1];
    12         }
    13         nums[0] = record;
    14         counter--;
    15     }
    16 }

     

转载于:https://www.cnblogs.com/hu-19941213/p/11011029.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值