LeetCode之Rotate Array
来源:互联网 发布:数据挖掘和搜索 编辑:程序博客网 时间:2024/06/01 19:28
1、题目
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.
2、结题思路
1、先得到有效的k,
2、反转所有数组
3、反转下标从0到k的数组
4、 反转下标从k到length - 1的数组
3、代码实现
class Solution {public void rotate(int[] nums, int k) { if (nums == null || nums.length == 0 || k <= 0) return; int length = nums.length; int lastK = 0; if (k < length) lastK = k; else lastK = k % length; if (lastK == 0) return; change(nums, length); change(nums, lastK); int i = lastK, j = length - 1; while (i < j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; i++; j--; } } public void change(int[] nums, int length) { for (int i = 0; i < length / 2; ++i) { int temp = nums[i]; nums[i] = nums[length - i - 1]; nums[length - i - 1] = temp; } }}
阅读全文
0 0
- leetcode 之Rotate Array
- leetcode之rotate array
- LeetCode之Rotate Array
- leetcode之Rotate Array
- Leetcode之Rotate Array
- LeetCode之Rotate Array
- Leetcode之Rotate Array 问题
- [leetcode][array] Rotate Array
- LeetCode之Rotate Array(C++)
- LeetCode 之 Rotate Array — C++ 实现
- 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
- java环境变量配置
- stm32学习笔记——外部中断的使用
- 第一篇博客
- IOS逆向--进行dylib的重新签名
- spring boot 自定义Controller,不能被扫描
- LeetCode之Rotate Array
- [Android优化]使用SparseArray和ArrayMap代替HashMap
- fabric源码解析16——peer的gossip服务之测试
- 【Ubuntu】win10和Ubuntu16.04双系统无法访问win10磁盘
- (十)stm32中FSMC的使用(用于LCD)
- void
- 算法分析与设计:leetcode169.Majority Element
- HBase数据存储格式
- ACM-9月17日周日周末训练心得