首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-189-Rotate Array

leetcode-189-Rotate Array

作者头像
chenjx85
发布2019-03-21 16:28:34
4110
发布2019-03-21 16:28:34
举报

题目描述:

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?

要完成的函数:

void rotate(vector<int>& nums, int k) 

说明:

1、这道题给定一个vector,要求将这个vector最右边的元素调到最左边,重复这个动作k次,最终结果仍然存放在nums中。要求空间复杂度为O(1)。

2、如果只使用一个临时变量来存放的话,这意味着我们要把最后一位取出来,然后其余位往后挪,再把临时变量放在第一位。重复这个动作k次。

笔者试了一下,超时了……

所以我们使用一个长度为k的vector来存放最后那k位,空间复杂度为O(k)。

代码如下:(附详解)

    void rotate(vector<int>& nums, int k) 
    {
        int s1=nums.size();
        k=k%s1;//如果nums=[1,2,3,4,5,6],k=11,我们要求余
        vector<int>temp(k,0);
        for(int i=0;i<k;i++)//把nums的后k位放在temp中
            temp[i]=nums[s1-k+i];
        for(int i=s1-k-1;i>=0;i--)//把nums的其余位往后挪k个位置
            nums[i+k]=nums[i];
        for(int i=0;i<k;i++)//把temp的数值放在nums的前k位
            nums[i]=temp[i];
    }

上述代码十分简洁,实测20ms,beats 96.80% of cpp submissions。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档