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

            }

        }

    }

     

  • 相关阅读:
    第12组 Beta冲刺 (4/5)
    第12组 Beta冲刺 (3/5)
    代码用辅助多了 基础的读取config都忘记了
    wpf 动态添加控件 通过xmal实习 c#代码插入控件
    C#里调用非托管的Dll -z注意 net版本
    动态调用 类库
    c#时间的生成
    c# 第三方 修改版本号 MSBuildTasks, 解决 通配符不匹配问题
    c#.exe以管理员身份运行
    log4
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363897.html
Copyright © 2011-2022 走看看