LeetCode(67)-Rotate Array
来源:互联网 发布:编程技术流 编辑:程序博客网 时间:2024/04/29 21:10
题目:
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); }}
0 0
- LeetCode(67)-Rotate Array
- [leetcode][array] Rotate Array
- LeetCode[Array]: Rotate Image
- LeetCode:Rotate Array
- [LeetCode] Rotate Array
- *LeetCode-Rotate Array
- [LeetCode]189.Rotate Array
- Rotate Array - LeetCode - Java
- Rotate Array--Leetcode(Java)
- Leetcode--Rotate Array
- LeetCode: Rotate Array
- LeetCode Rotate Array
- Rotate Array(leetcode)
- leetcode Rotate Array
- Leetcode: Rotate Array
- [Leetcode]11 Rotate Array
- [LeetCode][189][Rotate Array]
- Leetcode:Rotate Array
- linux 使用valgrind检查内存使用问题
- PL/SQL Developer配置免安装Oracle客户端
- Qt使用IE控件和屏蔽页面右键菜单
- HDU 2604 Queuing(矩阵快速幂)
- 服务器时间同步
- LeetCode(67)-Rotate Array
- iOS 自带二维码识别(识别二维码,条形码以及从相册中选择图片进行识别)
- 尼姆博弈之Matchs game
- android 利用mob 进行第三方登录
- TCP连接的“三次握手”与“四次挥手”
- Android 开发效率
- 关于ios中的转码问题
- 使用Express搭建HTTPs加密服务器
- 图文详解MyEclipse中新建Maven webapp项目的步骤(很详细)