Rotate Array

来源:互联网 发布:阮星竹 知乎 编辑:程序博客网 时间:2024/06/07 20:52

题目地址: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].

旋转数组,如果允许开辟出一个大小为k的数组,这个题目就简单多了:

public class RotateArray {    public static void rotate(int[] nums, int k) {        if (nums.length == 0)            return;        // 如果k大于数组的长度,那么移动的距离与对长度的求余是一致;        k %= nums.length;        int[] t = new int[k];        // 先把数组中最后k个元素搞出来        for (int i = 0; i < k; i++)            t[i] = nums[nums.length - k + i];        // 然后把前n-k个元素向后移动        for (int i = 0; i <= nums.length - 1 - k; i++) {            nums[nums.length - 1 - i] = nums[nums.length - 1 - i - k];        }        // 把上述保存的k个元素保存在数组的前k个位置上        for (int i = 0; i < k; i++) {            nums[i] = t[i];        }    }    public static void printArray(int[] nums){        for(int n : nums)            System.out.print(n + " ");    }    public static void main(String[] args) {        int[] nums = {1,2,3,4,5,6,7,8,9,10,11,12,13};        rotate(nums, 355);        printArray(nums);    }}

代码的逻辑也很简单,注释中已经说的很明白,最后k个代码保存,平均时间复杂度为O(n),前n-k个元素的移动平均时间复杂度为O(n),最后数组首部的填充时间复杂度也为O(n)。

所以该算法的时间复杂度为O(n),空间平均复杂度为O(n)。

0 0
原创粉丝点击