LeetCode-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].
經過k步旋轉一個有n個元素的數組

算法分析

方法一

需要一個額外的數組:通過給定的k和當前索引i,求得變換后對應的索引值。

Java代碼
public class Solution {
    public void rotate(int[] nums, int k) {
        int[] extraNum = new int[nums.length];
        for (int i = 0; i < nums.length; i ++) {
            extraNum[(i + k) % nums.length] = nums[i];//索引轉換
        }
        for (int i = 0; i < nums.length; i ++)
            nums[i] = extraNum[i];
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容