旋转数组

原题

  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]位置的数字进行反转,再对剩下的部分进行翻转。this

代码实现

算法实现类spa

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;
        }
    }
}
相关文章
相关标签/搜索