We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
出处:LeetCode 算法第75题 给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。 此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 注意: 不能使用代码库中的排序函数来解决这道题。 示例: 输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2] 进阶: 一个直观的解决方案是使用计数排序的两趟扫描算法。 首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 你能想出一个仅使用常数空间的一趟扫描算法吗?
出处:LeetCode 算法第75题
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意: 不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0] 输出: [0,0,1,1,2,2]
进阶:
方法1
var sortColors = function (nums) { var red = 0, white = 0, blue = 0; for (var i = 0, len = nums.length; i < len; i++) { if (nums[i] == 0) { red++; } else if (nums[i] == 1) { white++; } else { blue++; } } for (var i = 0; i < red; i++) { nums[i] = 0; } for (var i = red; i < red + white; i++) { nums[i] = 1; } for (var i = red + white; i < red + white + blue; i++) { nums[i] = 2; } };
方法2
var sortColors = function (nums) { var length = nums.length; if (length == 0) { return nums; } var head = 0, cursor = 0, tail = length - 1; while (cursor <= tail) { if (nums[cursor] == 0) { var temp = nums[head]; nums[head] = nums[cursor]; nums[cursor] = temp; cursor++; head++; } else if (nums[cursor] == 2) { var temp = nums[tail]; nums[tail] = nums[cursor]; nums[cursor] = temp; tail--; } else { cursor++; } } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
解答
方法1
方法2
The text was updated successfully, but these errors were encountered: