旋轉數組

原題

  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;
        }
    }
}
相關文章
相關標籤/搜索