Rotate Array---leetcode 我的java题解

来源:互联网 发布:淘宝联盟的导购推广位 编辑:程序博客网 时间:2024/04/28 18:32

原题连接 https://leetcode.com/problems/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.

[show hint]

Related problem: Reverse Words in a String II

分析: 

 rotate意思是把后面的数挪到最前面,k是几,就依次挪几个数。 我一开始还以为是以k位置为轴旋转呢,如果翻转的话,例子结果就变成了4567123了答案就不对了。看来理解题目意思多重要啊。
k的值也很关键。要注意边界。如果k的值比数组长度还大是允许的。就要进行取余的处理,否则越界。
三个办法实现这个题目:
public class RotateArray {    /*    第1种解法,研究rotate后的数组,找出规律。直接应用规律     */    public void reverse(int[] nums, int start, int end) {        while (start < end) {            int temp = nums[start];            nums[start] = nums[end];            nums[end] = temp;            start++;            end--;        }    }    public void rotate(int[] nums, int k) {        if (nums == null || nums.length == 0) return;        k = k % nums.length;        if (k == 0) return;        reverse(nums, 0, nums.length - 1);        reverse(nums, 0, k - 1);        reverse(nums, k, nums.length - 1);    }    //第2个解法 不断地把数组最后一个数挪到第一个位置上,挪k次。    public void rotate1(int[] nums, int k) {        //先判断输入参数是否合法        if ((nums != null) && (nums.length > 0) && (k > 0)) {            k %= nums.length;            while (k != 0) {                reverse1(nums);                k--;            }        }    }    //将数组最后一个数字移至头部    private void reverse1(int[] nums) {        int tail = nums[nums.length - 1];        for (int j = nums.length - 1; j > 0; j--) {            nums[j] = nums[j - 1];        }        nums[0] = tail;    }    //第3个解法,将k前面和k后面看成2个整体的部分。一起挪动。 引入了一个临时数组。    public void rotate3(int[] nums,int k){        int length=nums.length;        k=k%length;        if(nums.length==0||nums==null||k==0)            return;        int[] temp=new int[k];        for(int i=0;i<k;i++)            temp[i]=nums[length-k+i];        for(int i=nums.length-1-k;i>=0;i--)            nums[i+k]=nums[i];        for(int i=0;i<k;i++)            nums[i]=temp[i];    }    //测试数据    public void printArray(int[] C) {        for (int i = 0; i < C.length; i++) {            System.out.print(C[i] + " ");        }        System.out.println("\n");    }    public static void main(String[] args) {        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};        int k = 2;        RotateArray r = new RotateArray();        r.printArray(array);        r.rotate3(array, k);        r.printArray(array);    }}


0 0
原创粉丝点击