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

欢迎加入中科院开源软件自习室

原创粉丝点击