CShap 向量中的所有0移至末尾 源代码
时间: 2024-05-14 22:15:00 浏览: 104
以下是将C#向量中的所有0移至末尾的源代码:
```
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<int> vector = new List<int>(){1, 0, 5, 0, 9, 0, 3};
Console.WriteLine("Original Vector: [{0}]", string.Join(", ", vector));
vector = MoveZerosToEnd(vector);
Console.WriteLine("Modified Vector: [{0}]", string.Join(", ", vector));
}
public static List<int> MoveZerosToEnd(List<int> vector)
{
int count = vector.Count;
vector.RemoveAll(x => x == 0);
int zerosCount = count - vector.Count;
vector.AddRange(Enumerable.Repeat(0, zerosCount));
return vector;
}
}
```
运行结果:
```
Original Vector: [1, 0, 5, 0, 9, 0, 3]
Modified Vector: [1, 5, 9, 3, 0, 0, 0]
```
阅读全文