
我们需要三分球,低位、中位、高位。我们将在开头使用 low 和 mid 指针,而 high 指针将指向给定数组的末尾。
如果 array [mid] =0,则将 array [mid] 与 array [low] 交换] 并将两个指针递增一次。
如果 array [mid] = 1,则不需要交换。将中指针递增一次。
如果数组 [mid] = 2,则将数组 [mid] 与数组 [high] 交换,并将高指针递减一次。
时间复杂度 - O(N)
实时演示
using System;
namespace ConsoleApplication{
public class Arrays{
private void Swap(int[] arr, int pos1, int pos2){
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
public void DutchNationalFlag(int[] arr){
int low = 0;
int mid = 0;
int high = arr.Length - 1;
while (mid <= high){
if (arr[mid] == 0){
Swap(arr, low, mid);
low++;
mid++;
}
else if (arr[mid] == 2){
Swap(arr, high, mid);
high--;
}
else{
mid++;
}
}
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
int[] arr = { 2, 1, 1, 0, 1, 2, 1, 2, 0, 0, 1 };
a.DutchNationalFlag(arr);
for (int i = 0; i < arr.Length; i++){
Console.WriteLine(arr[i]);
}
Console.ReadLine();
}
}
}0 0 0 0 1 1 1 1 2 2 2
以上就是如何使用 C# 在没有额外空间的情况下对数组(荷兰国旗)中的 0,1,2 进行排序?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号