【LeetCode】Rotate Array 旋转数组
来源:互联网 发布:苹果手机怎样更新淘宝 编辑:程序博客网 时间:2024/06/06 08:51
题目
Rotate Array
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,将数组元素循环右移k位。
思路
三步翻转法,《编程珠玑》一书上有讲,步骤如下:
- 将数组从k位置分为前后两半;
- 翻转前半部分;
- 翻转后半部分;
- 翻转整个数组;
图示如下:
解答
Java代码如下,注意遍历时候的边界不要出错:
public void rotate(int[] nums, int k) { if(k==0 || nums==null ) return; k = k%nums.length; int tmp; for (int i = 0; i < (nums.length-k)/2; i++) { tmp = nums[i]; nums[i] = nums[nums.length-k-1-i]; nums[nums.length-k-1-i] = tmp; } /*for (int i : nums) { System.out.print(i+"-"); } System.out.println();*/ for (int i = 0; i < k/2; i++) { tmp = nums[i+nums.length-k]; nums[i+nums.length-k] = nums[nums.length-1-i]; nums[nums.length-1-i] = tmp; } /*for (int i : nums) { System.out.print(i+" "); } System.out.println();*/ for (int i = 0; i < nums.length/2; i++) { tmp = nums[i]; nums[i] = nums[nums.length-1-i]; nums[nums.length-1-i] = tmp; } }
0 0
- leetcode:Rotate Array旋转数组
- 【LeetCode】Rotate Array 旋转数组
- Rotate Array 数组旋转 leetcode
- leetcode Rotate Array 旋转数组
- LeetCode Rotate Array(数组的旋转)
- LeetCode 189 Rotate Array(旋转数组)
- LeetCode 189 Rotate Array(旋转数组)
- LeetCode 189. Rotate Array(旋转数组)
- leetcode 189. Rotate Array-旋转数组
- leetcode 189. Rotate Array旋转数组
- Rotate Array数组旋转
- 字符串,数组旋转问题-leetcode 189 Rotate Array
- Rotate Array 数组的旋转
- [C++]Rotate Array 旋转数组
- Rotate Array 部分旋转数组
- 189. Rotate Array 旋转数组
- 189. Rotate Array 旋转数组
- 189. Rotate Array (旋转数组)
- 性能测试几个常用俗语
- 【USACO 2015 Open Gold】Palindromic Paths 动态规划
- 项目管理的几种差评
- Linux 源
- java.lang.NoSuchMethodError找不到方法,但是那个方法明明存在
- 【LeetCode】Rotate Array 旋转数组
- 查看数据库版本
- 理发店模型之性能测试
- sql的简单提高效率方法
- web报表工具FineReport的JS编辑框和URL地址栏语法简介
- SSH框架中获取spring容器中的实体
- 网站
- 自编译 hadoop-2.5.2 x64安装包 下载
- 小白学Linux之内核模块编程