C# 修剪数组内的空格(删除 0)
如果我有下一个数组:
int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 };
如何将所有不等于 0 的值尽可能左移,以便数组将像这样构建:
int[] arr = { 123, 243, 123, 123, 0, 0, 0, 0, 0 };
谢谢!
If I have the next array:
int[] arr = { 123, 243, 0, 0, 123, 0, 0, 0, 123 };
How can I move all the values which are not equal to 0 left as they can so the array will be built like this:
int[] arr = { 123, 243, 123, 123, 0, 0, 0, 0, 0 };
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
LINQ 怎么样:
它非常可读并且具有线性时间复杂度。另一方面,它运行不合适,需要对输入进行两次传递。
How about with LINQ:
This is quite readable and has linear time complexity. On the other hand, it runs out-of-place and requires two passes over the input.
订购者:
OrderBy:
到目前为止的所有答案都会创建一个新数组。实际上,您可以在一个循环中向上移动项目,然后用 0 填充其余部分。
不像单行 LINQ 表达式那么优雅,但更高效 - 这不会创建任何新对象(并且 LINQ 创建几个和最终的新数组),并且这是对数组的单次传递。作为扩展方法,其复杂性在主体中看不到,它可以用作:
All the answers so far create a new array. Really you can just move the items up in a single loop and then fill the rest with 0s.
Not as elegant as the single line LINQ expressions, but more efficient - this does not create any new objects (and LINQ creates several and the final new array) and this is a single pass through the array. As an extension method the complexity is not seen in the main body where it can be used as:
或许可以使用 Linq:
Perhaps using Linq with:
试试这个:
Try this:
创建一个新数组并将值传输到其中。
由于
int
是值类型,因此数组初始化为全零。然后,如果值不为 0,我们一次复制一个值,仅增加目标索引i
。比所示的 Linq 示例更冗长,而且显然更不酷。但如果您是学生,可能会更容易理解。Make a new array and transfer the values to it.
Since
int
is a value type the array is initialized with all zeroes. Then we copy the values one at a time only increasing the destination indexi
if the value is not 0. More verbose than the Linq examples shown, and decidedly uncooler. But if you're a student it might be easier to follow.此代码片段不会创建另一个数组。这里“x[]”是您的数组。您获取第一个 0 值并将其替换为非零数字。
This code snippet doesn't create another array.Here 'x[]' is your array. You take the 1st 0 value and replace it with a non zero number.