Leetcode#189Rotate 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].

旋轉數組,採用的方法主要是,構造一箇中間數據,存儲旋轉後的結果,再將中間數組的結果寫回原數組

public class Solution {

    public void rotate(int[] nums, int k) {

        int l=nums.length;

        int w=k%l;

        int[] x=new int[l];

        for(int i=0;i<l;i++)

            x[i]=0;

        for(int i=l-w;i<l;i++)

            x[i-l+w]=nums[i];

        for(int i=0;i<l-w;i++)

            x[w+i]=nums[i];

        for(int i=0;i<l;i++)

            nums[i]=x[i];

    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章