zoukankan      html  css  js  c++  java
  • 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.

    此题想出来的第一个解题思路是整体旋转一次,然后0-(k-1)旋转一次,后面的数组元素再旋转一次,代码如下:

    public class Solution {

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

            k = k%(nums.length);

            rotatehelper(nums,0,nums.length-1);

            rotatehelper(nums,0,k-1);

            rotatehelper(nums,k,nums.length-1);

        }

        public void rotatehelper(int[] nums,int left,int right){

            int l = left;

            int r = right;

            while(l<r){

                int temp = nums[l];

                nums[l] = nums[r];

                nums[r] = temp;

                l++;

                r--;

            }

        }

    }

    第二种方法是把原来的数组元素放到排好序的新数组里面,然后新数组的值赋值回原数组里面,代码如下:

    public class Solution {

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

            int[] num = new int[nums.length];

            for(int i=0;i<nums.length;i++){

                num[(i+k)%(nums.length)] = nums[i];

            }

            for(int i=0;i<num.length;i++){

                nums[i] = num[i];

            }

        }

    }

     

  • 相关阅读:
    eslint 的 env 配置是干嘛使的?
    cookie httpOnly 打勾
    如何定制 antd 的样式(theme)
    剑指 Offer 66. 构建乘积数组
    剑指 Offer 65. 不用加减乘除做加法
    剑指 Offer 62. 圆圈中最后剩下的数字
    剑指 Offer 61. 扑克牌中的顺子
    剑指 Offer 59
    剑指 Offer 58
    剑指 Offer 58
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363897.html
Copyright © 2011-2022 走看看