leetcode 热题 100_轮转数组

题解一:

        新数组存储:另外用一个数组存储移动后的结果,再复制回原数组。

class Solution {
    public void rotate(int[] nums, int k) {
        int[] result = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            result[(i + k) % nums.length] = nums[i];
        }
        System.arraycopy(result, 0, nums, 0, nums.length);
    }
}

题解二:

        原数组移动:在原数组上直接将nums[i]移动到nums[i+k],需要临时存储被覆盖的值nums[i+k],被覆盖的值则继续向后移动覆盖nums[i+2k],循环直到回到第一个开始移动的值。,这个过程可能有若干元素没有被移动,因此需要从nums[i+1]开始重复这个过程。如何判断所有的值都被移动过一次呢,另外用一个count计数,每次移动都+1,直到等于数组长度。这个解法效率较低并且较难理解,不推荐。

class Solution {
    public void rotate(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        int count = 0;

        for (int i = 0; count < n; i++) {
            for (int pre = nums[i], next, index = i; ; ) {
                next = (i + k) % n;

                int temp = nums[next];
                nums[next] = pre;
                pre = temp;

                count++;

                i = (i + k) % n;
                if (i == index) break;
            }
        }
    }

}

题解三:

        数组翻转:将整个数组进行反转,再以下标[0,k-1][k,nums.length-1]左右两段分别进行翻转就得到最终结果,很巧妙的解法。

class Solution {
    public void reserve(int[] a, int begin, int end) {
        for (; begin < end; begin++, end--) {
            int temp = a[begin];
            a[begin] = a[end];
            a[end] = temp;
        }
    }

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

相关推荐

  1. 轮转数组 - LeetCode 15

    2024-03-11 14:26:03       40 阅读
  2. 力扣100_普通数组_189_轮转数组

    2024-03-11 14:26:03       42 阅读
  3. LeetCode经典150Golang版.189. 轮转数组

    2024-03-11 14:26:03       68 阅读
  4. LeetCode】面试经典150:189.轮转数组

    2024-03-11 14:26:03       28 阅读
  5. Leetcode100

    2024-03-11 14:26:03       54 阅读
  6. LeetCode100

    2024-03-11 14:26:03       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-11 14:26:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-11 14:26:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-11 14:26:03       82 阅读
  4. Python语言-面向对象

    2024-03-11 14:26:03       91 阅读

热门阅读

  1. leetcode热题HOT leetcode131. 分割回文串

    2024-03-11 14:26:03       45 阅读
  2. Linux的Vim/vi中注释详细教程

    2024-03-11 14:26:03       46 阅读
  3. Linux的Vim/vi中注释详细教程

    2024-03-11 14:26:03       40 阅读
  4. WebGL之灯光使用解析

    2024-03-11 14:26:03       32 阅读
  5. Django——模板

    2024-03-11 14:26:03       41 阅读
  6. 动态规划 Leetcode 746 使用最小花费爬楼梯

    2024-03-11 14:26:03       41 阅读
  7. 网络层学习常见问题及答案整理

    2024-03-11 14:26:03       42 阅读