{ "question_id": 75, "question_title": "颜色分类", "difficulty": "中等", "question_content": "

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

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

 

示例 1:

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

示例 2:

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

示例 3:

输入:nums = [0]
输出:
[0]

示例 4:

输入:nums = [1]
输出:
[1]

 

提示:

 

进阶:

", "topic_link": "https://bbs.csdn.net/topics/600470126", "cpp": "#include \nusing namespace std;\nclass Solution\n{\npublic:\n\tvoid sortColors(vector &nums)\n\t{\n\t\tint i = 0, j = nums.size() - 1;\n\t\twhile (i < j)\n\t\t{\n\t\t\tif (nums[i] == 0)\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (nums[j] != 0)\n\t\t\t{\n\t\t\t\tj--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tswap(nums[i], nums[j]);\n\t\t}\n\t\tj = nums.size() - 1;\n\t\twhile (i < j)\n\t\t{\n\t\t\tif (nums[i] == 1)\n\t\t\t{\n\t\t\t\ti++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (nums[j] != 1)\n\t\t\t{\n\t\t\t\tj--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tswap(nums[i], nums[j]);\n\t\t}\n\t}\n};", "java": "class Solution {\n\tpublic void sortColors(int[] nums) {\n\t\tint low = 0, high = nums.length - 1;\n\t\tint i = 0;\n\t\twhile (i <= high) {\n\t\t\tif (nums[i] == 0) {\n\t\t\t\tint tmp = nums[i];\n\t\t\t\tnums[i] = nums[low];\n\t\t\t\tnums[low] = tmp;\n\t\t\t\t++low;\n\t\t\t\t++i;\n\t\t\t} else if (nums[i] == 1) {\n\t\t\t\t++i;\n\t\t\t} else if (i <= high && nums[i] == 2) {\n\t\t\t\tint tmp = nums[i];\n\t\t\t\tnums[i] = nums[high];\n\t\t\t\tnums[high] = tmp;\n\t\t\t\t--high;\n\t\t\t}\n\t\t}\n\t}\n}", "js": "", "python": "class Solution(object):\n\tdef sortColors(self, nums):\n\t\tlow, mid, high = 0, 0, len(nums) - 1\n\t\twhile mid <= high:\n\t\t\tif nums[mid] == 0:\n\t\t\t\tnums[low], nums[mid] = nums[mid], nums[low]\n\t\t\t\tlow += 1\n\t\t\t\tmid += 1\n\t\t\telif nums[mid] == 1:\n\t\t\t\tmid += 1\n\t\t\telse:\n\t\t\t\tnums[high], nums[mid] = nums[mid], nums[high]\n\t\t\t\thigh -= 1\n\t\treturn nums\n# %%\ns = Solution()\nprint(s.sortColors(nums = [2,0,2,1,1,0]))", "status": 1, "keywords": "数组,双指针,排序", "license": { "cpp": "https://github.com/begeekmyfriend/leetcode", "python": "https://github.com/qiyuangong/leetcode", "java": "https://blog.csdn.net/a1439775520/article/details/104343861" }, "notebook": { "cpp": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/74/74_cpp.ipynb?type=file", "python": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/74/74_python.ipynb?type=file", "java": "https://codechina.csdn.net/csdn/csdn-daily-code/-/jupyter/master/data/notebook/leetcode/ipynb/74/74_java.ipynb?type=file" }, "notebook_enable": 1 }