LeetCode075——颜色分类

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/sort-colors/description/

题目描述:

LeetCode075——颜色分类

知识点:三路快排

思路一:两趟扫描

第一趟扫描记录0、1和2的数量,第2趟扫描重写当前数组。

时间复杂度是O(n),其中n为nums数组的长度。空间复杂度是O(1)。

JAVA代码:

public class Solution {

    public void sortColors(int[] nums) {
        int red = 0;
        int white = 0;
        int blue = 0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == 0){
                red++;
            }else if(nums[i] == 1){
                white++;
            }else{
                blue++;
            }
        }
        for (int i = 0; i < red; i++) {
            nums[i] = 0;
        }
        for (int i = red; i < red + white; i++) {
            nums[i] = 1;
        }
        for (int i = red + white; i < red + white + blue; i++) {
            nums[i] = 2;
        }
    }
}

LeetCode解题报告:

LeetCode075——颜色分类

思路二:三路快排

题目虽然套上了颜色分类的面具,其本质其实是三路快速排序算法的实现。

时间复杂度是O(n),其中n为nums数组的长度。空间复杂度是O(1)。

JAVA代码:

public class Solution {

    public void sortColors(int[] nums) {
        int lessThan = -1;                   //[0, lessThan] restore 0
        int greaterThan = nums.length;      //[greaterThan, nums.length - 1] restore 2
        int i = 0;                          //[lessThan + 1, i) restore 1
        while(i < greaterThan){
            if(nums[i] == 0){
                swap(nums, i, lessThan + 1);
                lessThan++;
                i++;
            }else if(nums[i] == 1){
                i++;
            }else{
                swap(nums, i, greaterThan - 1);
                greaterThan--;
            }
        }
    }

    private void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

LeetCode解题报告:

LeetCode075——颜色分类