Rotate Array
来源:互联网 发布:矩阵音箱的作用 编辑:程序博客网 时间:2024/06/08 09:26
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.
2 解题思路
是一个简单题,主要考察对于数组的操作,理解了题意就可以写,有多种写法。
3 源代码
package com.larry.easy;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class RotateArray {public void rotate(int[] nums, int k) { int len = nums.length; if(k >= len) k %= len; List<Integer> list = new ArrayList<Integer>(); for(int i = len-k; i < len; i++) list.add(nums[i]); for(int i = 0; i < len-k; i++) nums[len-1-i] = nums[len-k-i-1]; for(int i = 0; i < k; i++) nums[i] = list.get(i); }public static void main(String[] args) {/*int[] nums = {1,2,3,4,5,6,7};int k = 3;*//*int[] nums = {1,2};int k = 3;*/int[] nums = {1,2,3};int k = 1;RotateArray ra = new RotateArray();ra.rotate(nums, k);System.out.println(Arrays.toString(nums));}}
0 0
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- rotate array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Rotate Array
- Eight(South Central USA 1998)
- Myeclipse快捷键
- cocos2dx-lua捕获用户touch事件的几种方式
- matlab GUI常用文件操作对话框
- #104 Maximum Depth of Binary Tree
- Rotate Array
- 在eclipse/myeclipse调试时老挂起的问题
- LeetCode222 Count CompleteTree Nodes(计算完全二叉树的节点数) Java 题解
- 图像差值算法
- 简单的java加密算法
- [LeetCode][Java] Remove Nth Node From End of List
- 修改界面顶部状态栏的颜色
- Powershell 操作SQL Server
- mianshi_experience