当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.189.Rotate Array 旋转数组

LeetCode.189.Rotate Array 旋转数组

题目描述

189 Rotate Array
https://leetcode-cn.com/problems/rotate-array/

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?


解题过程

这道题的标准解法就是三次翻转,翻转前n-k个数,翻转后k个数,最后翻转整个数组。
《编程珠玑》 第二章 2.3 节 讲了这个算法,还给出了一个翻手示例图。
时间复杂度 O(n),空间复杂度 O(1)

private static class SolutionV2020 {
    public void rotate(int[] nums, int k) {
        if (null == nums || nums.length == 0 || (k % nums.length) == 0) {
            return;
        }
        // k 先对长度求余,防止溢出
        k = k % nums.length;
        reverse(nums, nums.length - k, nums.length - 1);
        reverse(nums, 0, nums.length - k - 1);
        reverse(nums, 0, nums.length - 1);
    }

    private void reverse(int[] nums, int left, int right) {
        if (null == nums || left == right) {
            return;
        }
        for (; left < right; left++, right--) {
            int temp = nums[right];
            nums[right] = nums[left];
            nums[left] = temp;
        }
    }
}

GitHub代码

algorithms/leetcode/leetcode/_189_RotateArray.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_189_RotateArray.java


上一篇 LeetCode.061.Rotate List 旋转链表

下一篇 LeetCode.260.Single Number III 数组中只出现一次的数3

阅读
评论
347
阅读预计1分钟
创建日期 2020-02-17
修改日期 2020-02-17
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论