LeetCode Rotate Array
来源:互联网 发布:js判断是否为质数 编辑:程序博客网 时间:2024/06/06 19:44
Description:
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.
Solution:
有这么几种方法:
1. 重新new一个数组
2. 向右循环k次
3. 比较巧妙。将数组分为两个部分,前面n-k个和后面的k个,下标分别是[0, n-k-1]和[ n-k, n-1]。然后前后两个区间都分别倒置,最后再将整个区间倒置。
import java.util.*;public class Solution {public void rotate(int[] nums, int k) {int n = nums.length;k = k % n;reverse(nums, 0, n - k - 1);reverse(nums, n - k, n - 1);reverse(nums, 0, n - 1);}void reverse(int[] nums, int start, int end) {int c;for (int i = start, j = end; i < j; i++, j--) {c = nums[i];nums[i] = nums[j];nums[j] = c;}}}
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
- [转]PHP 5.2~5.6 对比以及功能详解
- 南阳oj 题目34 韩信点兵
- 在Mac下配置php开发环境:Apache+php+MySql
- HtmlParser基础教程
- 字符串相乘(算法)
- LeetCode Rotate Array
- [转]LNMP环境下的Web常见问题排查(精品)
- 移动端高清、多屏适配方案
- 【独立开发者er Cocos2d-x实战 002】使用Cocos Studio创建帧动画
- 数据结构与算法-约瑟夫问题
- Java解析HTML之HTMLParser使用与详解
- 244 16进制的简单运算
- Count the Colors
- 今天开始写博客