如何在不使用任何额外空间的情况下使用 C# 对数组中的 0 和 1 进行排序?
获取两个指针 low 和 high。 我们将 low 指针用在开始处,high 指针将指向给定数组的末尾。
如果数组 [low] = 0,则不需要交换
如果数组 [low] = 1,则需要交换。 high 指针随后需要减一。
时间复杂度 − O(N)
示例
using System;
namespace ConsoleApplication{
public class Arrays{
public void SwapZerosOnes(int[] arr){
int low = 0;
int high = arr.Length - 1;
while (low < high){
if (arr[low] == 1){
Swap(arr, low, high);
high--;
}
else{
low++;
}
}
}
private void Swap(int[] arr, int pos1, int pos2){
int temp = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = temp;
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
int[] arr1 = { 0, 1, 1, 0, 1, 1 };
a.SwapZerosOnes(arr1);
for (int i = 0; i < arr1.Length; i++){
Console.WriteLine(arr1[i]);
}
}
}
}输出
0 0 1 1 1 1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP