博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode-189-Rotate Array
阅读量:7115 次
发布时间:2019-06-28

本文共 1274 字,大约阅读时间需要 4 分钟。

题目描述:

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 = 3Output: [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 = 2Output: [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
& nums, int k) { int s1=nums.size(); k=k%s1;//如果nums=[1,2,3,4,5,6],k=11,我们要求余 vector
temp(k,0); for(int i=0;i
=0;i--)//把nums的其余位往后挪k个位置 nums[i+k]=nums[i]; for(int i=0;i

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

转载于:https://www.cnblogs.com/chenjx85/p/9105793.html

你可能感兴趣的文章
webstorm快捷键 webstorm keymap内置快捷键英文翻译、中英对照说明
查看>>
热修改 MySQL 数据库 pt-online-schema-change 的使用详解
查看>>
Android调试优化篇
查看>>
Linux技巧汇总
查看>>
EF框架step by step(8)—Code First DataAnnotations(2)
查看>>
MySQL 若干操作
查看>>
Apache Rewrite规则详解
查看>>
JSON 之JAVA 解析
查看>>
MVC5网站开发之一 总体概述
查看>>
windows编程之菜单操作
查看>>
关键路径法
查看>>
Java并发编程:线程和进程的创建(转)
查看>>
【转】如何利用logrotate工具自动切分滚动中的日志文件
查看>>
视频摘要视频浓缩
查看>>
wow.js使用方法
查看>>
ContentPlaceHolderID属性
查看>>
源码安装Memcached服务器及其2种PHP客户端
查看>>
大数据架构:flume-ng+Kafka+Storm+HDFS 实时系统组合
查看>>
QT 对话框一
查看>>
mysql加密函数
查看>>