leetcode 75. 颜色分类 中等 排序

题目:
在这里插入图片描述

分析:直接用进阶的一趟扫描来做。可以用两个变量分别指向0的末尾,2的起始,用一个指针指向当前需要比较的元素。
遇到0的时候,当前元素与0末尾交换,然后两个指针都+1,;遇到2的时候当前元素与2的起始交换,2的起始-1,当前不变(因为交换过来后还需要比较);遇到1,当前指针+1,其余不变

代码:

class Solution {
    public void sortColors(int[] nums) {
        int one_end = 0;
        int current = 0;
        int two_start = nums.length-1;
        while(current <= two_start){
            if(nums[current] == 2){
                exchange(nums, current, two_start);
                two_start--;
            }else if(nums[current] == 0){
                exchange(nums, current, one_end);
                current++;
                one_end++;
            }else{
                current++;
            }
        }
    }

    void exchange(int[] nums, int a, int b){
        int temp = nums[b];
        nums[b] = nums[a];
        nums[a] = temp;
    }
}

在这里插入图片描述
在这里插入图片描述

发布了134 篇原创文章 · 获赞 17 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_40208575/article/details/105168863
今日推荐