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
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
n
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
0
1
2
Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
The text was updated successfully, but these errors were encountered:
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var sortColors = function(nums) { let red = 0; let blue = nums.length - 1; let i = 0; while (i <= blue) { if (nums[i] === 0) { swap(nums, i++, red++); } else if (nums[i] === 2) { swap(nums, i, blue--); } else { i++; } } }; function swap(nums, x, y) { let temp = nums[x]; nums[x] = nums[y]; nums[y] = temp; }
/** Do not return anything, modify nums in-place instead. */ function sortColors(nums: number[]): void { let red = 0; let blue = nums.length - 1; let i = 0; while (i <= blue) { if (nums[i] === 0) { swap(nums, i++, red++); } else if (nums[i] === 2) { swap(nums, i, blue--); } else { i++; } } } function swap(nums: number[], x: number, y: number) { let temp = nums[x]; nums[x] = nums[y]; nums[y] = temp; }
Sorry, something went wrong.
No branches or pull requests
75. Sort Colors
给定一个包含红色、白色和蓝色,一共
n
个元素的数组,原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。此题中,我们使用整数
0
、1
和2
分别表示红色、白色和蓝色。Example
Note
Follow up
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
The text was updated successfully, but these errors were encountered: