1. 程式人生 > >【LeetCode-面試演算法經典-Java實現】【189-Rotate Array(旋轉陣列)】

【LeetCode-面試演算法經典-Java實現】【189-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].
  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; } } }

評測結果

  點選圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中檢視完整圖片。

這裡寫圖片描述

特別說明