zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【算法hot100】颜色分类(75)

算法 分类 颜色 75
2023-09-27 14:29:28 时间

颜色分类(75)

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

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

必须在不使用库的sort函数的情况下解决这个问题。

示例 1:

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sort-colors
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:

public class LC020_75_sortColors_01 {

    public static void main(String[] args) {
        int[] nums = new int[]{2, 0, 2, 1, 1, 0};
        sortColors(nums);
    }

    public static void sortColors(int[] nums) {
        Arrays.sort(nums);
    }
}

解法二:

public class LC020_75_sortColors_02 {

    public static void main(String[] args) {
        int[] nums = new int[]{2, 0, 2, 1, 1, 0};
        sortColors(nums);
    }

    public static void sortColors(int[] nums) {
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (num == 0) {
                swap(nums, i, index);
                index++;
            }
        }
        for (int i = index; i < nums.length; i++) {
            int num = nums[i];
            if (num == 1) {
                swap(nums, i, index);
                index++;
            }
        }
    }

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

解法三:

public class LC020_75_sortColors_03 {
    public static void main(String[] args) {
        int[] nums = new int[]{2, 0, 2, 1, 1, 0};
        sortColors(nums);
    }

    public static void sortColors(int[] nums) {
        int index1 = 0, index2 = 0;
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (num == 1) {
                swap(nums, i, index2);
                index2++;
            } else if (num == 0) {
                swap(nums, i, index1);
                if (index1 < index2) {
                    swap(nums, i, index2);
                }
                index1++;
                index2++;
            }
        }
    }

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

解法四:

public class LC020_75_sortColors_04 {
    public static void main(String[] args) {
        int[] nums = new int[]{2, 0, 2, 1, 1, 0};
        sortColors(nums);
    }

    public static void sortColors(int[] nums) {
        int n = nums.length;
        int left = 0, right = n - 1;
        for (int i = 0; i < n; i++) {
            while (nums[i] == 2 && i <= right) {
                swap(nums, i, right);
                right--;
            }
            if (nums[i] == 0) {
                swap(nums, i, left);
                left++;
            }
        }
    }

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