zoukankan      html  css  js  c++  java
  • LeetCode 189. 旋转数组(Rotate Array)

    189. 旋转数组

    LeetCode189. Rotate Array

    题目描述
    给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。

    示例 1:
    输入: [1,2,3,4,5,6,7] 和 k = 3
    输出: [5,6,7,1,2,3,4]
    解释:
    向右旋转 1 步: [7,1,2,3,4,5,6]
    向右旋转 2 步: [6,7,1,2,3,4,5]
    向右旋转 3 步: [5,6,7,1,2,3,4]

    示例 2:
    输入: [-1,-100,3,99] 和 k = 2
    输出: [3,99,-1,-100]
    解释:
    向右旋转 1 步: [99,-1,-100,3]
    向右旋转 2 步: [3,99,-1,-100]

    说明:

    • 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
    • 要求使用空间复杂度为 O(1) 的原地算法。

    Java 实现
    双重循环

    import java.util.Arrays;
    
    class Solution {
        /**
         * 双重循环
         * 时间复杂度:O(kn)
         * 空间复杂度:O(1)
         */
        public void rotate(int[] nums, int k) {
            int n = nums.length;
            k %= n;
            for (int i = 0; i < k; i++) {
                int temp = nums[n - 1];
                for (int j = n - 1; j > 0; j--) {
                    nums[j] = nums[j - 1];
                }
                nums[0] = temp;
            }
        }
    
        public static void main(String[] args) {
            Solution solution = new Solution();
            int[] nums = {1, 2, 3, 4, 5, 6, 7};
            int k =3;
            solution.rotate(nums, k);
            System.out.println(Arrays.toString(nums));
        }
    }
    

    运行结果

    [5, 6, 7, 1, 2, 3, 4]
    

    翻转

    import java.util.Arrays;
    
    class Solution {
        /**
         * 翻转
         * 时间复杂度:O(n)
         * 空间复杂度:O(1)
         */
        public void rotate(int[] nums, int k) {
            int n = nums.length;
            k %= n;
            reverse(nums, 0, n - 1);
            reverse(nums, 0, k - 1);
            reverse(nums, k, n - 1);
        }
    
        private void reverse(int[] nums, int start, int end) {
            while (start < end) {
                int temp = nums[start];
                nums[start++] = nums[end];
                nums[end--] = temp;
            }
        }
    
        public static void main(String[] args) {
            int[] nums = {1, 2, 3, 4, 5, 6, 7};
            Solution solution = new Solution();
            solution.rotate(nums, 3);
            System.out.println(Arrays.toString(nums));
        }
    }
    

    运行结果

    [5, 6, 7, 1, 2, 3, 4]
    

    参考资料

  • 相关阅读:
    回调函数(C语言)
    main函数的参数(一)
    术语,概念
    [LeetCode] Invert Binary Tree
    关于overload和override
    第一个只出现一次的字符
    Manacher算法----最长回文子串
    C++对象模型
    回文判断
    字符串转换成整数
  • 原文地址:https://www.cnblogs.com/hgnulb/p/10798602.html
Copyright © 2011-2022 走看看