Bra*_*don 12 java arrays algorithm performance
目前我有一个大小为N的数组.我正在尝试从数组中复制每个X字节数.
例如,如果数组大小为10,我想要大小为3的数组.我将复制前3个元素,然后复制下3个元素和最后1个元素.
目前我正在使用以下算法:
int I = 0;
int sub = bytes.length;
int counter = 0;
for (I = 0; I < bytes.length; ++I) {
if (I % 3 == 0 && I != 0) {
NewArray[counter] = Arrays.copyOfRange(bytes, I - 3, I));
sub -= 3;
++counter;
}
}
NewArray[counter] = Arrays.copyOfRange(bytes, I - sub, I)); //Copy remainder.
Run Code Online (Sandbox Code Playgroud)
有没有更有效或更体面的方式来做我想要的?这个算法看起来很糟糕= l
我有什么想法可以改进它或者至少提示一下吗?
ars*_*jii 10
那这个呢:
int x = 3; // chunk size
int len = bytes.length;
int counter = 0;
for (int i = 0; i < len - x + 1; i += x)
newArray[counter++] = Arrays.copyOfRange(bytes, i, i + x);
if (len % x != 0)
newArray[counter] = Arrays.copyOfRange(bytes, len - len % x, len);
Run Code Online (Sandbox Code Playgroud)
这是一个将a转换byte[]为数组的方便方法byte[].所以,结果是byte[][].
public byte[][] splitBytes(final byte[] data, final int chunkSize)
{
final int length = data.length;
final byte[][] dest = new byte[(length + chunkSize - 1)/chunkSize][];
int destIndex = 0;
int stopIndex = 0;
for (int startIndex = 0; startIndex + chunkSize <= length; startIndex += chunkSize)
{
stopIndex += chunkSize;
dest[destIndex++] = Arrays.copyOfRange(data, startIndex, stopIndex);
}
if (stopIndex < length)
dest[destIndex] = Arrays.copyOfRange(data, stopIndex, length);
return dest;
}
Run Code Online (Sandbox Code Playgroud)
与之前的最佳答案相比有些优点:
for条件使用<=,这使得比更有意义< ... + 1.if块中的计算次数.(单元测试)