LeetCode(67)-Rotate Array
2016-04-21 12:24
387 查看
题目:
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.
思路:
题意:要求对给定长度的整形数组n进行平移,给定k,就平移3个位置(循环)要求是在o(1)的空间,不能考虑数组的复制了,根据算法,这个平移转化为逆序。reverse(nums,0,n-k-1),reverse(nums,n-k,n-1),reverse(nums,0,n-1)等价,写一个reverse的函数。
代码:
public class Solution { public void reverse(int[] nums,int start,int end){ while(start < end){ int tmp = nums[start]; nums[start] = nums[end]; nums[end] = tmp; start++; end--; } } public void rotate(int[] nums, int k) { if(nums.length == 0){ return; } int n = nums.length; k = k%n; reverse(nums,0,n-k-1); reverse(nums,n-k,n-1); reverse(nums,0,n-1); } }
相关文章推荐
- LeetCode(67)-Rotate Array
- android 利用mob 进行第三方登录
- 4G红米NOTUSB调试---fwqlzz love is for ever
- 利用Linux系统生成随机密码的10种方法
- HDU 2604 Queuing(矩阵快速幂)
- Angular.js中使用$watch监听模型变化
- 服务器时间同步
- PL/SQL Developer配置免安装Oracle客户端
- HDU 2604 Queuing(矩阵快速幂)
- 进制转换
- LVS IP TUNL模式
- [置顶] UI设计资源收集
- leetcode_091 Decode Ways
- C#:几种数据库的大数据批量插入
- 推荐一个用C++实现类关系的英文博文
- 认识一下Kotlin语言,Android平台的Swift
- Error:Unable to run mksdcard SDK tool in ubuntu
- 免费的论文查重网站
- JDBC学习第一天
- SaltStack