LeetCode 75 颜色分类(荷兰旗问题)

给定一个包含红色、白色和蓝色,一共 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。

注意:
不能使用代码库中的排序函数来解决这道题。

示例:

输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]

进阶:

  • 一个直观的解决方案是使用计数排序的两趟扫描算法。
    首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
  • 你能想出一个仅使用常数空间的一趟扫描算法吗?

思路:此题其实就是‘荷兰旗问题’。

设置3个指针begin、current、end :begin end标记已排好序的0和2   current进行动态调整

注意:0和2排好序时 1自然排好 故1不需要处理

class Solution {
    public void sortColors(int[] nums) {
//         设置3个指针 begin end current 注意交换的顺序问题
        for(int begin=0,end=nums.length-1,current=0;current<=end;){
            if(nums[current]<1) {
                swap(nums,current,begin);
                begin++;
                current++;
            }
            else if(nums[current]==1){
                current++;
            }
            else {
                swap(nums,current,end);
                end--;
            }
        }
    }
    public void swap(int nums[],int i,int j){
        int temp=nums[i];
        nums[i]=nums[j];
        nums[j]=temp;
    }
}

猜你喜欢

转载自blog.csdn.net/Z_Y_D_/article/details/83744406
今日推荐