LeetCode OJ 189. Rotate Array
2016-05-19 17:52
302 查看
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
【思路一】
这个题目的意思是把数组尾部的n = (K%nums.length)个元素移动到数组的前面。一个最简单的想法就是把后面n个元素依次往前移动即可。代码如下:
这样做空间复杂度为O(1),但是时间复杂度较高,如何改进呢?
【思路二】
例如:[1,2,3,4,5,6,7] k = 3
先将5以前的数据翻转得到的数组是[4,3,2,1,5,6,7]
再将5及以后的数据翻转得到的数组是[4,3,2,1,7,6,5]
再将整个数组翻转即得到[5,6,7,1,2,3,4]
代码如下:
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.
[show hint]
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
【思路一】
这个题目的意思是把数组尾部的n = (K%nums.length)个元素移动到数组的前面。一个最简单的想法就是把后面n个元素依次往前移动即可。代码如下:
public class Solution { public void rotate(int[] nums, int k) { if(nums==null || nums.length <= 0) return; int n = k % nums.length; for(int i = 0; i < n; i++){ for(int j = nums.length - n + i; j > i; j--){ int temp = nums[j-1]; nums[j-1] = nums[j]; nums[j] = temp; } } } }
这样做空间复杂度为O(1),但是时间复杂度较高,如何改进呢?
【思路二】
例如:[1,2,3,4,5,6,7] k = 3
先将5以前的数据翻转得到的数组是[4,3,2,1,5,6,7]
再将5及以后的数据翻转得到的数组是[4,3,2,1,7,6,5]
再将整个数组翻转即得到[5,6,7,1,2,3,4]
代码如下:
public class Solution { public void rotate(int[] nums, int k) { if(nums==null || nums.length <= 0 || k%nums.length==0) return; int length = nums.length; k = k%length; reversal(nums, 0, length - k - 1); reversal(nums, length -k, length - 1); reversal(nums, 0, length - 1); } public void reversal(int[] nums, int i, int j){ int t = 0; while(i < j && i >= 0){ t = nums[i]; nums[i] = nums[j]; nums[j] = t; i++; j--; } } }
相关文章推荐
- ambari无法登陆 设备空间不足
- java Socket实现简单在线聊天(二)
- iOS 极光推送
- memcached 并发原语CAS与GETS操作
- ubuntu下ibus-sunpinyin输入法安装配置
- Python学习笔记—PyQuery库的使用总结
- Spring MVC 流程图
- struts2详细工作流程
- android 任务Task及回收栈back stack介绍
- 2位数乘1位数
- 不会编辑了,求救
- Python3学习笔记(urllib模块的使用)转http://www.cnblogs.com/Lands-ljk/p/5447127.html
- Lesson 3 Time Complexity PermMissingElem
- android 任务Task及回收栈back stack介绍
- 1乘1
- 连续奇数和
- Java基础---泛型
- commons-httpclient post请求乱码问题记录(非编码问题,gzip格式问题)
- 注册码生成器 略屌略屌
- 浅谈MVP in Android