189. Rotate Array
来源:互联网 发布:飞机模拟驾驶软件 编辑:程序博客网 时间:2024/06/11 14:18
189. 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个步骤。
例如,在n = 7和k = 3的情况下,[1,2,3,4,5,6,7]旋转数组[5,6,7,1,2,3,4]。
注意:
尽可能提出尽可能多的解决方案,至少有3种不同的方法来解决这个问题。
解题思路
主要的思路就是多存一个临时数组,把要换到前面的数组存进去,然后进行换顺序,其中需要特别注意的是k的值会比nums的长度多,那个时候需要做一个k=k%nums.length的处理,这里很巧妙
public class Solution { public void rotate(int[] nums, int k) { if(k <= 0) return; k=k%nums.length; if(k==0) return; int []tem=new int[k]; for(int i=0;i<k;i++){ tem[i] = nums[nums.length-k+i]; } for(int i=nums.length-1;i>=k;i--){ nums[i]=nums[i-k]; } for(int i=0;i<k;i++){ nums[i]=tem[i]; } }}
欢迎加入中科院开源软件自习室:631696396
阅读全文
0 0
- Leetcode - Array - 189. Rotate Array
- 189. Rotate Array leetcode(array)
- LeetCode-Array-189. Rotate Array
- [LeetCode]189.Rotate Array
- [Leetcode] 189.Rotate Array
- LeetCode 189. Rotate Array
- 【LeetCode】189.Rotate Array
- [leetcode] 189.Rotate Array
- 【leetcode】189. Rotate Array
- Leetcode 189. Rotate Array
- 189. Rotate Array LeetCode
- 189. Rotate Array
- [LeetCode]189. Rotate Array
- 189. Rotate Array
- leetcode-189.-Rotate Array
- 189. Rotate Array
- 189. Rotate Array
- 189. Rotate Array
- bat(批处理)基本操作
- 监控摄像头如何进行互联网网页实时直播
- 模板网站
- Matlab的运算符
- codeforce : Educational Codeforces Round 22
- 189. Rotate Array
- Tomcat服务器的监听及宕机自动重启的开发
- AndroidStudio1.4创建项目的build.gradle(Module:app)中的配置
- 函数之闭包
- php新特性你知道多少
- bzoj3143/洛谷3434 游走 高斯消元求期望
- 从《人民的名义》看智慧园区运行监控可视化
- 多线程总结
- matplotlib基础