如何利用C++、C、Python对0、1、2数组进行排序

99 阅读1分钟

问题

给出一个只包含0、1和2的数组。请写出一个有效的算法来对该数组进行排序。

输入样本

[2, 0, 1, 1]

输出示例

[0, 1, 1, 2]

蛮力

你可以直接使用任何排序算法来完成这个任务。这将花费O(NLogN)时间和至少O(N)辅助空间。我们能找到一个更好的方法吗?

高效的方法

这个问题可以用一个3个指针的方法来解决。让我们看看怎么做!

有三个指针。 start, idxfinish. 开始 存储第一个非0的索引 。 finish 存储最后一个非2的索引,而 idx 将从 开始结束

如果该元素是0,则用索引 开始处的元素替换它 ,并更新 start = start + 1idx = idx + 1.

如果该元素是1,那么 idx = idx + 1 应该被更新。

如果元素是2,用索引 结束处的元素替换它 ,并更新 finish = inish – 1.

这种方法的时间复杂度为O(N),辅助空间为O(1)。

C++编程

#include<bits/stdc++.h>
using namespace std;

void sortArray(vector<int>& nums) {
        int n=nums.size();
        if(n==1) return;
        int start=0;
        int finish=n-1;
    
        

C语言编程

#include<stdio.h>
void sortArray(int nums[], int numsSize){
    int finish = numsSize -1;
    int start = 0;
    int idx = 0;
    while (idx <= finish)
    {
        if (nums[idx] == 0)
        {
            int save = nums[start];
            nums[start] = nums[idx];
            nums[idx] = save;
            idx++; start++;
        }
        else if (nums[idx] == 1)
        {
            idx++;
        }
        else
        {
            int temp = nums[finish];
            nums[finish] = nums[idx];
            nums[idx] = temp;
            finish--;
        }
    }
}
void main(){
    int nums[4] = {1, 1, 0, 2};
    sortArray(nums, 4);
    for(int i=0; i<4; i++) printf("%d ",nums[i]);
}

Python编程

def sortArray(a):
        idx = 0
        start = 0
        finish = len(a) - 1
        while idx <= finish:
            if a[idx] == 0:
                a[idx], a[start] = a[start], a[idx]
                idx += 1
                start += 1
            elif a[idx] == 1:
                idx += 1
            else:
                a[idx], a[finish] = a[finish], a[idx]
                finish -= 1
        return a
        
l = [1, 1, 0, 2]
print(sortArray(l))

输出

[0, 1, 1, 2]