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

            }

        }

    }

     

  • 相关阅读:
    “Hello World!”团队第七次Scrum立会
    20170928-2 单元测试,结对
    20170928-4 每周例行报告
    20170928-3 四则运算试题生成
    20170928-1 代码规范,结对要求
    软件工程第六次作业——例行报告
    软件工程第四次作业-2单元测试
    软件工程第四次作业-4每周例行报告
    软件工程第四次作业-3四则运算
    软件工程第四次作业-1代码规范
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363897.html
Copyright © 2011-2022 走看看