做到这一点最有效的方法是什么?
我有一个大小为 N 的数组 array
。对于其中的每 3 个索引,我想将它们取出并声明并将这些值分配给另一个大小为 3 的数组。然后我想返回到该数组并取出下一个 3 并将其放入大小为 3 的不同数组中。完成后,我将像这样迭代 3 个大小为 3 a1,a2,a3
的不同数组清空 a1,a2,a3
并将 NEXT 3 个值重新添加到大小为 3 的 3 个数组中,重复此操作,直到达到 array.length
什么是最好/最这样做的有效方法?
I've got an array array
of size N. For every 3 indexes in it I want to take them out and declare and assign those values to another array of size 3. I then want to go back to that array and take the next 3 and put it in a different array of size 3. I'll iterate like this for 3 different arrays of size 3 a1,a2,a3
once this is done I want to empty a1,a2,a3
and re add the NEXT 3 values to the 3 arrays of size 3 repeating this on till we reach array.length
What would be the best / most efficient way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
作为一般策略,我一开始不会担心效率。
尽可能明确地对其进行编码,然后编写大量单元测试来确认其有效。迭代地提高性能。
使正确的代码变得更快比使快速的代码变得正确更容易。
As a general strategy I would not worry about efficiency at first.
Code it as explicitly as possible, and then write a load of unit tests confirming it works. The iteratively improve performance.
Its easier to make correct code fast than it is to make fast code correct.
这是一种非常脆弱但快速的方法。每次都会覆盖之前的值,因此无需清除。如果您确实需要清除 arrayN,只需在循环后使用 Arrays.fill(arrayN, null) 即可。
编辑:对于不太脆弱的答案,我假设您会膨胀 mxn 数组。不要硬编码 a1, a2, ... am,而是创建一个二维数组
a[m][n]
。并且,正如 Adrian 在评论中建议的那样,在循环外部声明 i 并使用其相对于 N 的值来酌情处理剩余部分。
That's a pretty brittle but fast way of doing it. Each time the previous values are overwritten, so no need to clear. If you do need to have
arrayN
clear, you can justArrays.fill(arrayN, null)
after the loop.EDIT: For the less brittle answer, I'm going to assume you'd be inflating m x n arrays. Instead of hard coding a1, a2, ... am, make a 2D array
a[m][n]
.and, as Adrian suggests in the comments, declare
i
outside the loop and use its value relative to N to deal with leftovers as appropriate.非常简单,您可以按照以下方式完成......
下面是代码片段...
byte[] YourBigArray = new byte[SomeValue];
int 温度 = 0;
while(temp < YourBigArray.size - 1 )
{
System.arrayCopy(YourBigArray, temp,smallarray, 0, 3);
温度+=3;
尝试这个代码
并查看 arrayCopy 函数的文档......
享受......
Its very easy, you can do it in the following way....
It is code snippet below....
byte[] YourBigArray = new byte[SomeValue];
int temp = 0;
while(temp < YourBigArray.size - 1 )
{
System.arrayCopy(YourBigArray, temp, smallarray, 0, 3);
temp+=3;
}
Try this code and also see the documentation of arrayCopy function....
Enjoy.....