博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Rotating an array in place
阅读量:6252 次
发布时间:2019-06-22

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

 

April 13, 2010 in 

Rotate a one-dimensional array of n elements to the right by k steps. 

For instance, with n=7 and k=3, the array {a, b, c, d, e, f, g} is rotated to {e, f, g, a, b, c, d}.

 

In my previous post we discussed about finding an element in a rotated array. You might ask, how do we rotate an array?

The straight forward way is to allocate a temporary array of size n, and then copy elements starting from index k to the new array, and copy it back to the old array. This is highly inefficient because:

    1. It needs extra space to store a temporary array (O(n) space).

 

    1. It involves back-and-forth copying, a total of 2*n copy operations.

 

So, the question is, can we do this more efficiently, preferably an in-place rotation method.

The answer is of course, yes. This is a trick so important that it becomes one of the frequently asked interview questions. An in-depth discussion is in , one of the must-read book in Computer Science.

The trick is to do three reverse operation. One for the entire string, one from index 0 to k-1, and lastly index k to n-1. Magically, this will yield the correct rotated array, without any extra space! (Of course, you need a temporary variable for swapping).

 

 

转载于:https://www.cnblogs.com/leetcode/p/4012465.html

你可能感兴趣的文章
原型 、原型链和对象是怎么实现继承的
查看>>
layui中select切换数据_layui 下拉框 动态获取数据
查看>>
佳能hdr_内置HDR功能 佳能5D3特色拍摄功能解析
查看>>
matlab和python转换_将MATLAB代码转换为Python:Python类型和操作顺序
查看>>
jmeter3000用户压测_jmeter集群压测搭建
查看>>
转子接地保护原理_发变组保护动作逻辑
查看>>
hive中groupby优化_面试必备技能-HiveSQL优化
查看>>
uni 页面加载完毕_HTML页面生命周期
查看>>
c语言机票座位预定系统_趁东京奥运!日航要免费送5万张国内机票!给非日本居民...
查看>>
创业冲突的五种解决方法是_冲突管理的五种策略
查看>>
lsmw中文显示乱码_中文注释不能在keil 4/5中正常显示——都是方框或乱码?
查看>>
hcg值小于0.1_【原理】JavaScript 中 0.1 + 0.2 为什么不等于 0.3?
查看>>
springboot的jsp应该放在哪_健身小白用2个月亲身经历告诉你小白去健身房,应该做到哪几点...
查看>>
opencv表面缺陷检测_工业产品表面缺陷检测方法
查看>>
kettle使用数据库来生成序列_时间序列数据库Influxdb的使用
查看>>
配置babel_关于 Babel 你必须知道的
查看>>
数据丢失与重复_消息队列重复消费和数据丢失问题(石衫面试突击学习笔记)...
查看>>
摄像头 火狐_为什么谷歌浏览器打不开电脑摄像头?
查看>>
两张图片合成一张_ps技巧:大光比照片后期曝光合成技法
查看>>
码条形码属性_条码生成器如何批量生成code 11码
查看>>