Rotate Array

来源:互联网 发布:到淘宝买港版手机 编辑:程序博客网 时间:2024/06/02 03:00
/* * 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]. * */
//第一种方法public class Solution {public static void main(String[] agrs){   int[] nums = {1,2,3,4,5,6,7};   rotate(nums, 3);   for(int x : nums)   System.out.print(x+" ");}public static void rotate(int[] nums, int k) {        int numsLength = nums.length;        k = k%numsLength;        reverse(nums, 0, numsLength-1);//先对整个数组进行反转        reverse(nums, 0, k-1);//对前k个数进行反转        reverse(nums, k, numsLength-1);//后几个数反转    }public static void reverse(int[] nums,int start,int end){while(start < end){int temp = nums[start];nums[start] = nums[end];nums[end] = temp;start++;end--;}}}

//第二种方法

public static void rotate(int nums[],int k) {         int numsLength = nums.length;         k = k%numsLength;         int[] tmp = new int[numsLength];         for(int i = 0 ; i < numsLength ; i++)         {         tmp[i] = nums[i];         }         for(int i = 0 ; i < numsLength ; i++)         {         nums[(i+k)%numsLength] = tmp[i];         }   }


0 0
原创粉丝点击