【LeetCode-面试算法经典-Java实现】【189-Rotate Array(旋转数组)】

【189-Rotate Array(旋转数组)】


【LeetCode-面试算法经典-Java实现】【所有题目目录索引】


代码下载【https://github.com/Wang-Jun-Chao】

原题

  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个位置。

解题思路

  先将k转换成[0, n-1]内的数。再对整个数组进行翻转,再对[0, k-1]位置的数字进行反转,再对剩下的部分进行翻转。

代码实现

算法实现类

public class Solution {
    public void rotate(int[] nums, int k) {
        k = (nums.length + (k % nums.length)) % nums.length; // 保证k为正

        int tmp;
        for (int i = 0, j = nums.length - 1; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        for (int i = 0, j = k - 1; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }

        for (int i = k, j = nums.length - 1; i < j; i++, j--) {
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
    }
}

评测结果

  点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。

【LeetCode-面试算法经典-Java实现】【189-Rotate Array(旋转数组)】_第1张图片

特别说明

欢迎转载,转载请注明出处【http://blog.csdn.net/derrantcm/article/details/47945385】

你可能感兴趣的:(LeetCode,LeetCode)