记录下自己拙计的算法之旅 LeetCode Rotate Array
2015-04-12 20:56
106 查看
记录下自己拙计的算法之旅
**LeetCode
Rotate Array:**
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
语言 ruby
空间复杂度为O(n),时间复杂度O(n),拙计~~
另一种方法
但是时间复杂度为O(n^2),空间为O(1),直接Time Limit Exceeded,更拙计 = =
**LeetCode
Rotate Array:**
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
语言 ruby
def rotate(nums, k) num_cp = nums.clone pos = k % nums.length start_pos = 0 nums.length.times do nums[pos] = num_cp[start_pos] start_pos += 1 pos += 1 pos %= nums.length end end
空间复杂度为O(n),时间复杂度O(n),拙计~~
另一种方法
def rotate2 nums, k nums_length = nums.length k = k % nums_length return if k == 0 || nums_length == 1 k.times do temp = nums[nums_length-1] point = nums_length-1 point.times do nums[point] = nums[point-1] point -= 1 end nums[0] = temp end end
但是时间复杂度为O(n^2),空间为O(1),直接Time Limit Exceeded,更拙计 = =
相关文章推荐
- BM25算法 仅供自己记录学习
- 算法学习ing,自己做个记录
- 记录《自己动手写网络爬虫 》书中涉及的内容学习一些算法
- 记录一些自己看到的算法
- 轻松编写您自己的拖拉机算法,进行算法大战
- 3月24日 想到了一个字符串匹配的新算法 程序 时间复杂度自己不会算
- 开始记录算法历程
- [导入]WebbUpload测试的输入记录,用来安慰一下自己!!
- 自己写的一个JSP小游戏21点,记录一下
- 利用高级Java、算法、三角学、分布计算设计自己的智能机器人
- 【原创】密码升级:超级可变、抗记录、自己易记的密码
- 轻松编写您自己的拖拉机算法,进行算法大战
- 自己写的算法对日期进行加减
- 利用高级Java、算法、三角学、分布计算设计自己的智能机器人--(重锤痛击续2)
- 翻出一段自己以前写的求最大子串和的算法
- 在java语言计算数据库记录总数的简便算法
- 一年没有更新自己的BLOG了,主要是记录一些从sqlserver导数据到oracle的解决方法
- 刚收到微软通知笔试的邮件,记录自己的心情。
- 轻松编写您自己的拖拉机算法,进行算法大战
- 自己动手,丰衣足食——一个简单却高效的图像旋转算法