如何使用 C# 将给定的整数数组中所有的零移动到数组的末尾?
创建 MoveZeros 方法,遍历该数组并计算数组中的零的数量。根据计数大小,将所有最后的单元格都设为零。如果数组长度为 null 或空,则返回而不处理。最终结果将出现在 nums 数组中。时间复杂度为 O(N),因为我们只遍历数组一次。
时间复杂度 − O(N)
空间复杂度 − O(1)
示例
public class Arrays{
public void MoveZeros(int[] nums){
if (nums == null || nums.Length == 0){
return;
}
int count = 0;
for (int i = 0; i < nums.Count(); i++){
if (nums[i] != 0){
nums[count] = nums[i];
count++;
}
}
for (int i = count; i < nums.Length; i++){
nums[i] = 0;
}
}
}
static void Main(string[] args){
int[] nums = { 0, 1, 0, 3, 12 };
s.MoveZeros(nums);
foreach (var item in nums){
Console.WriteLine(item);
}
}输出
[1,3,12,0,0]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP