Rotate Array

来源:互联网 发布:网站数据库设计 编辑:程序博客网 时间:2024/06/07 08:35

Description:

Create a method named “rotate” that returns a given array with the elements inside the array rotated n spaces.

If n is greater than 0 it should rotate the array to the right. If n is less than 0 it should rotate the array to the left. If n is 0, then it should return the array unchanged.

Example:

Object[] data = new Object[]{1, 2, 3, 4, 5};rotate(data, 1)    =>    {5, 1, 2, 3, 4}rotate(data, 2)    =>    {4, 5, 1, 2, 3}rotate(data, 3)    =>    {3, 4, 5, 1, 2}rotate(data, 4)    =>    {2, 3, 4, 5, 1}rotate(data, 5)    =>    {1, 2, 3, 4, 5}rotate(data, 0)    =>    {1, 2, 3, 4, 5}rotate(data, -1)    =>    {2, 3, 4, 5, 1}rotate(data, -2)    =>    {3, 4, 5, 1, 2}rotate(data, -3)    =>    {4, 5, 1, 2, 3}rotate(data, -4)    =>    {5, 1, 2, 3, 4}rotate(data, -5)    =>    {1, 2, 3, 4, 5}

Furthermore the method should take ANY array of objects and perform this operation on them:

rotate(new Object[]{'a', 'b', 'c'}, 1)        =>    {'c', 'a', 'b'}rotate(new Object[]{1.0, 2.0, 3.0}, 1)        =>    {3.0, 1.0, 2.0}rotate(new Object[]{true, true, false}, 1)    =>    {false, true, true}

Finally the rotation shouldn’t be limited by the indices available in the array. Meaning that if we exceed the indices of the array it keeps rotating.

Example:

Object[] data = new Object[]{1, 2, 3, 4, 5}rotate(data, 7)        =>    {4, 5, 1, 2, 3}rotate(data, 11)       =>    {5, 1, 2, 3, 4}rotate(data, 12478)    =>    {3, 4, 5, 1, 2}

算法思想:

三次反转数组:第一次反转整个数组;第二次反转数组的 n 个数;第三次反转数组剩下的数

若是正数:

一维数组  [1,2,3,4,5], n = 3第一次反转:5,4,3,2,1第二次反转:3,4,5,2,1第三次反转:3,4,5,1,2

若是负数:

一维数组  [1,2,3,4,5], n = -3第一次反转:5,4,3,2,1第二次反转:5,4,1,2,3第三次反转:4,5,1,2,3

My Solutions:

public class Rotator {    public Object[] rotate(Object[] data, int n) {       if (n >= 0) {            n %= data.length;            reverse(data, 0, data.length - 1);            reverse(data, 0, n - 1);            reverse(data, n, data.length - 1);        }else{            n = Math.abs(n%data.length);            reverse(data, 0, data.length - 1);            reverse(data, data.length - n, data.length - 1);            reverse(data, 0, data.length - n - 1);          }        return data;  }    public void reverse(Object[] data, int start, int end){        while (start < end) {            Object temp = data[start];            data[start] = data[end];            data[end] = temp;            start++;            end--;        }    }}
0 0
原创粉丝点击