Leetcode 189. Rotate Array

来源:互联网 发布:管理车间 软件系统 编辑:程序博客网 时间:2024/04/30 02:43

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

The idea is from http://www.programcreek.com/2015/03/rotate-array-in-java/, The trick is to reverse the array

public static void rotate(int[] arr, int order) {order = order % arr.length; if (arr == null || order < 0) {throw new IllegalArgumentException("Illegal argument!");} //length of first partint a = arr.length - order;  reverse(arr, 0, a-1);reverse(arr, a, arr.length-1);reverse(arr, 0, arr.length-1); } public static void reverse(int[] arr, int left, int right){if(arr == null || arr.length == 1) return; while(left < right){int temp = arr[left];arr[left] = arr[right];arr[right] = temp;left++;right--;}}


0 0
原创粉丝点击