• 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.

    [show hint]

    Hint:
    Could you do it in-place with O(1) extra space?
    Related problem: Reverse Words in a String II


    三段翻转。
    Time: O(n)
    Space: O(n)

    public class Solution {
        public void rotate(int[] nums, int k) {
            if (nums.length == 0 || k % nums.length == 0) return;
            k %= nums.length;
            reverse(nums, 0, nums.length - 1);
            reverse(nums, 0, k - 1);
            reverse(nums, k, nums.length - 1);
        }
        
        public void reverse(int[] nums, int l, int r) {
            while (l < r) {
                int temp = nums[l];
                nums[l++] = nums[r];
                nums[r--] = temp;
            }
            return;
        }
    }
    

    正常做得用个O(n)的数据结构。

    GOOGLE有个SHIFT的题,follow up要求in-place without 三段。。

    试一试。。

    1 2 3 4 5 6 7 = > 5 6 7 1 2 3 4
    1 2 3 1 5 6 7 t = 4
    1 2 3 1 5 6 4 t = 7
    1 2 7 1 5 6 4 t = 3
    1 2 7 1 5 3 4 t = 6
    1 6 7 1 5 3 4 t = 2
    1 6 7 1 2 3 4 t = 5
    5 6 7 1 2 3 4..done..
    从第一个开始,每次移K个位置,总共移动nums.length个

    这个CASE表明移nums.length个不行的。。会回到原点
    1 2 3 4 = > 3 4 1 2
    1 2 1 4 t = 3

    所以回到远点我们就到下一个。。总共还是nums.length

    嘿嘿。。做出来了

    public class Solution {
        public void rotate(int[] nums, int k) {
            if (nums.length == 0 || k % nums.length == 0) return;
            k %= nums.length;
            int done = 0;
            for (int i = 0; i < k; i++) {
                int j = i;
                int tempVal = nums[i];
                while (done < nums.length) {
                    int tempJ = (j + k) % nums.length;
                    int temp = nums[tempJ];
                    nums[tempJ] = tempVal;
                    tempVal = temp;
                    j = tempJ;
                    done++;
                    if (j == i) break;
                }
            }
        }
    }
    
  • 相关阅读:
    关闭弹出窗体,刷新父页面
    Oracle 导出部分表结构,以及导入
    ORCLE报错解决(ora01747:无效的用户.表.列,表.列)
    PL/SQL Developer使用技巧
    自定义table
    Array查询数组中是否包含指定字符
    水晶报表去掉多余小数点
    HttpHandler HttpModule入门篇
    窗口类名无效 错误 解决方法
    2020.10.15
  • 原文地址:https://www.cnblogs.com/reboot329/p/6056137.html
Copyright © 2020-2023  润新知