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];

            }

        }

    }

     

  • 相关阅读:
    Jetson Nano更改软件源
    树莓派开机启动VNC
    树莓派VNC复制粘贴
    数学之美-泰勒公式
    C++顺序容器
    eigen的简单用法汇总
    C++并发-同步并发
    C++ string类
    C++并发-互斥元
    Nginx常用命令
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363897.html
Copyright © 2011-2022 走看看