leetcode Rotate Array
来源:互联网 发布:php 表单数据提交 编辑:程序博客网 时间:2024/06/07 02:37
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.
[show hint]
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
虽然是一道easy的题目,但自己想到的解法都出现超时的情况,网上看到一个很好的解法,下面举个例子:
如1 2 3 4 5 6 7 k=3
以5为边界,翻转5之前的数字:4 3 2 1 5 6 7
然后翻转5与5之后的数字:4 3 2 1 7 6 5
翻转整个数组:5 6 7 1 2 3 4 完成。
对此我只能说,数学很神奇。。。
代码:
public void rotate(int[] nums, int k) { int len=nums.length; if(k>=len) k%=len; reverse(nums,0,len-k-1); reverse(nums,len-k,len-1); reverse(nums,0,len-1);}public void reverse(int[] a,int i,int j){ int temp; for(;i<j;i++,j--){ temp=a[i]; a[i]=a[j]; a[j]=temp; }}
0 0
- [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
- LeetCode: Rotate Array
- 我不是产品经理-003
- 编程问题汇总(vsprintf函数的缺陷)
- Android版本和API Level对应关系
- 2015ACM-ICPC 北京赛区 Problem K. A Math Problem
- Yii2.0配置pathinfo
- leetcode Rotate Array
- Linux下scp的用法
- BloomFilter(布隆过滤器)的C#实现
- HDU3085 Nightmare Ⅱ 双向bfs
- surfaceview
- python中字符串
- HBase数据库访问封装
- WebView常用方法详解及h5新特性
- vm下的centos设置网络