LeetCode Rotate Array(数组的旋转)
2015-07-20 18:53
387 查看
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array
rotated to
题意:给出一个数组,让其右移k 位,求新的数组
思路:先将[0,len-1]翻转,再[0,k-1]之间翻转,[k,len-1]之间翻转
代码如下
public class Solution
{
public void rotate(int[] nums, int k)
{
int len = nums.length;
int i = 0, j = len - 1;
while (i < j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
if (k > len) k -= len;
i = 0;
j = k - 1;
while (i < j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
i = k;
j = len - 1;
while (i < j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
}
}
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].
题意:给出一个数组,让其右移k 位,求新的数组
思路:先将[0,len-1]翻转,再[0,k-1]之间翻转,[k,len-1]之间翻转
代码如下
public class Solution
{
public void rotate(int[] nums, int k)
{
int len = nums.length;
int i = 0, j = len - 1;
while (i < j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
if (k > len) k -= len;
i = 0;
j = k - 1;
while (i < j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
i = k;
j = len - 1;
while (i < j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
}
}
相关文章推荐
- (剑指Offer)面试题29:数组中出现次数超过一半的数字
- 解决Zabbix自定义用户参数无法获取到数据的问题
- 解决Zabbix自定义用户参数无法获取到数据的问题
- 【回文串】 Jisuanke 商品推荐走马灯(中等)
- HTML字符实体 使用说明
- CTRun CTLine
- TEX Quotes
- js 跨域问题
- HDUOJ1001
- 苹果开发 笔记(51)TextKit
- VI normal command summary
- EF框架中加子类后出现列名 'Discriminator' 无效问题
- java:自定义异常
- 动态加载xml文件
- OC语言字符串的多种方法
- day05
- HDU 4283 You Are the One 区间DP
- 约束以及修改数据表
- linuxshell 求列和
- (1.5.2.0)编程之美思路总结