[leetcode]Rotate Array

来源:互联网 发布:vb程序设计培训班 编辑:程序博客网 时间:2024/06/02 01:21

题目描述如下:

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]
提示:尝试尽可能多的方法来实现,至少有三种方法可以解决这个问题。

第一种方法很容易想到开一个新的数组保存最后的K个数字,然后将其余的数字往后移动K步,再把新数组里的数字保存到开头。唯一需要注意的是考虑k大于n的情况,所以先对n取余。代码一遍AC:

public class Solution {   public void rotate(int[] nums, int k) {            k = k % nums.length;            int tmp[] = new int[k];            int i;            for(i = nums.length - k; i < nums.length; i++){                tmp[i + k - nums.length] = nums[i];            }            for(i = nums.length - 1; i >= k; i--){                    nums[i] = nums[i  - k];            }            for(i = 0; i < k; i++){                nums[i] = tmp[i];            }        }}

其实后来才看到hint里面说要在O(1)的时间内完成….

既然要三种方法,还有两个思路:

1、将数组中的数字转换成String,然后用String截取字符串并重新拼接,最后还原成数组;

2、对于第K个关键节点(从后往前数),先将该节点以前的数据翻转,再将该节点及以后的数据翻转,最后将整个数组翻转。

以上两个仅为思路,并没有实际测过正确性。

题目链接:https://leetcode.com/problems/rotate-array/

0 0
原创粉丝点击