leetcode 189. Rotate Array旋转数组
来源:互联网 发布:装配式建筑缺点 知乎 编辑:程序博客网 时间:2024/06/06 01:56
题目描述:
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].
解题思路:
数组向右进行旋转,每旋转n次恢复原状,所以k要mod n得到简化后的旋转次数。最先想到的是新建一个整型数组,分两部分进行,存储旋转后的数组,最后修改原数组nums中的顺序。
代码:
class Solution { public void rotate(int[] nums, int k) { int n = nums.length; int[] result = new int[n]; int num = k % n; for (int i = n - num, j = 0; i < n && j<n; i++,j++){ result[j] = nums[i]; } for (int i = 0,j = num; i<n && j<n;i++,j++){ result[j] = nums[i]; } for(int i = 0;i<n;i++){ nums[i] = result[i]; } }}
改进:
由于新建了一个数组,造成了内存空间的占用,想办法仅仅利用数组nums进行旋转。基本的想法是:例如数组为 nums = [1,2,3,4,5,6,7] 且 k = 3。首先,我们翻转[1,2,3,4],变为[4,3,2,1];然后我们翻转[5,6,7],变为[7,6,5];最后我们翻转整个数组,[4,3,2,1,7,6,5] —> [5,6,7,1,2,3,4].
代码:
class Solution { public void rotate(int[] nums, int k) { if(nums == null || nums.length <2){ return; } int num = k % nums.length; reverse(nums,0,nums.length-1-num); reverse(nums,nums.length-num,nums.length-1); reverse(nums,0,nums.length-1); } public void reverse(int[] nums, int i,int j){ while(i<j){ int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; i++; j--; } }}
阅读全文
0 0
- LeetCode 189. Rotate Array(旋转数组)
- leetcode 189. Rotate Array-旋转数组
- leetcode 189. Rotate Array旋转数组
- leetcode:Rotate Array旋转数组
- 【LeetCode】Rotate Array 旋转数组
- Rotate Array 数组旋转 leetcode
- leetcode Rotate Array 旋转数组
- 189. Rotate Array 旋转数组
- 189. Rotate Array 旋转数组
- LeetCode Rotate Array(数组的旋转)
- LeetCode 189 Rotate Array(旋转数组)
- LeetCode 189 Rotate Array(旋转数组)
- Rotate Array数组旋转
- 189. Rotate Array (旋转数组)
- 字符串,数组旋转问题-leetcode 189 Rotate Array
- Rotate Array 数组的旋转
- [C++]Rotate Array 旋转数组
- Rotate Array 部分旋转数组
- Error:Execution failed for task ':app:mergeDebugResources'. > Error: java.util.concurrent.ExecutionE
- 认识分支结构if
- 匿名内部类----应用
- pygame安装说明
- kafka的自学之路---zookeeper中的存储结构
- leetcode 189. Rotate Array旋转数组
- idea旗舰版破解
- jq ajax返回值保存为全局变量
- 小白的起步——MVP
- 双目鱼眼标定工具编写思考
- 简单解决Ubuntu修改locale的问题
- CodeForces 872C Maximum splitting
- java常用设计模式
- window下配置SSH连接GitHub、GitHub配置ssh key