2020

    科技2024-01-26  101

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

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

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

    示例:

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

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

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

    两遍扫描的方法非常直观:

    class Solution { public void sortColors(int[] nums) { int[] c = new int[3]; for(int i : nums) { ++c[i]; } int i = 0, j = 0; while(j < 3) { while(c[j] > 0) { nums[i++] = j; --c[j]; } ++j; } } }

    一遍扫描无非是各种交换位置,随便挑了一个实现:

    class Solution { void swap(int[] nums, int a, int b) { int t = nums[a]; nums[a] = nums[b]; nums[b] = t; } public void sortColors(int[] nums) { int p0 = 0, cur = 0, p2 = nums.length - 1; //p0 下一个0的位置 cur 当前扫描 p2 下一个2的位置 while(cur <= p2) { switch(nums[cur]) { case 0: swap(nums, p0, cur); ++p0; ++cur; break; case 1: ++cur; break; case 2: swap(nums, p2, cur); --p2; break; } } } }

    实现起来感觉有点像在实现快速排序一样TAT

    Processed: 0.009, SQL: 8