【发布时间】:2018-10-08 17:05:00
【问题描述】:
我有一个简单的旋转函数,它需要一个数组和一个数字来旋转左边的数字
例如[1,2,3,4,5] & 2 - 输出:[3,4,5,1,2]。
我想知道完成这个功能最有效的方法,是将int数组转换为字符串拼接还是复制数组或转换为List<Integer>。
如果有人想了解更多信息,请询问!
我目前的解决方案:
static int[] rotLeft(int[] a, int d) {
int lengthOfArray = a.length;
int[] temp = new int[lengthOfArray];
for(int i = 0; i < lengthOfArray; i++){
int newLocation = (i + (lengthOfArray - d)) % lengthOfArray;
temp[newLocation] = a[i];
}
return temp;
}
【问题讨论】:
-
您能否展示您当前的解决方案以及您为什么认为它效率不高?
-
您不需要额外的
collection来执行此操作。您可以使用数组本身来做到这一点。 -
@NicholasK 可以解释一下吗?
-
阅读
Collections.rotate(List, int)的文档。将其应用于数组。 -
@aidan22 : 为什么不先将所有输入存储在数组中,然后将其向左移动?