C# 二维数组快速移位方法
我在 C# 中有一个 2D 字符串数组,我需要将该数组在一维中向左移动 我怎样才能以有效的方式做到这一点
我不想使用嵌套 for 并且我想要 O(n) 而不是 O(n2) 的算法
for (int i = 50; i < 300; i++)
{
for (int j = 0; j < 300; j++)
{
numbers[i-50, j] = numbers[i, j];
}
}
I have a 2D string array in C# and I need to shift that array to left in one dimension
how can I do that in efficient way
I dont want use nested for and i want an algurithm in O(n) not O(n2)
for (int i = 50; i < 300; i++)
{
for (int j = 0; j < 300; j++)
{
numbers[i-50, j] = numbers[i, j];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想快速移动大量数据,请使用 Array.Copy 而不是复制单个字符的循环。
如果您交换到字节数组并使用 Array.Copy 或 Buffer.BlockCopy ,您可能会进一步提高性能(但如果您必须转换为字符或从字符转换)数组你可能会失去你所获得的一切)。
(编辑:既然您已经发布了示例代码):如果您使用对数组行的引用,那么您可能可以移动引用,而不必移动数据本身。任何你仍然可以使用 Array.Copy 移动引用)
但是如果你改变你的方法,这样你就不需要移动数据,你将获得更好的性能 - 如果你可以避免它总是不做工作快点!您可能可以将数据包装在访问器层中,该访问器层跟踪数据已移动的量并修改索引以返回您想要的数据。 (这会稍微减慢对数据的访问速度,但可以节省您移动数据的时间,因此可能会带来净胜利 - 取决于您访问的量相对于您移动的量)
If you want to shift large amounts of data around quickly, use
Array.Copy
rather than a loop that copies individual characters.If you swap to a byte array and use
Array.Copy
orBuffer.BlockCopy
you will probably improve the performance a bit more (but if you have to convert to/from character arrays you may lose everything you've gained).(edit: Now that you've posted example code): If you use references to the array rows then you may be able to shift the references rather than having to move the data itself. Any you can still shift the references using Array.Copy)
But if you change your approach so you don't need to shift the data, you'll gain considerably better performance - not doing the work at all if you can avoid it is always faster! Chances are you can wrap the data in an accessor layer that keeps track of how much the data has been shifted and modifies your indexes to return the data you are after. (This will slightly slow down access to the data, but saves you shifting the data, so may result in a net win - depending on how much you access relative to how much you shift)
最有效的方法是根本不改变它,而是改变访问数组的方式。例如,保留一个偏移量来告诉您第一列在维度中的位置。
The most efficient way would be to not shift it at all, but instead change how you access the array. For example, keep an offset that tells you where in the dimension the first column is.