189 Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?

解釋下題目:

數(shù)組的數(shù)字往后推移k位,如果超出了最后則接到頭部

1. 倒置的方法

實際耗時:0ms

    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int tmp = nums[start];
            nums[start] = nums[end];
            nums[end] = tmp;
            start++;
            end--;
        }
    }
踩過的坑:[-1] k=2

??我自己想到的思路是有三種,第一種是,搞個函數(shù),然后這個函數(shù)的作用是每次給數(shù)組后退1格,然后如果是k的話就重復(fù)k次,這樣時間是O(nk) 不需要額外的空間。第二種是再開辟一個同樣大小的數(shù)組,很簡單。最后一種就是上面代碼里的,其實這種rotate的題目最后都可以用倒序來實現(xiàn)。

時間復(fù)雜度O(n)
空間復(fù)雜度O(1)

表名1 表名2
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容