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
Difficulty: 中等
Related Topics: 数组, 双指针, 排序
给定一个包含红色、白色和蓝色、共 n个元素的数组 nums ,对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
n
nums
我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
0
1
2
必须在不使用库的sort函数的情况下解决这个问题。
示例 1:
输入:nums = [2,0,2,1,1,0] 输出:[0,0,1,1,2,2]
示例 2:
输入:nums = [2,0,1] 输出:[0,1,2]
提示:
n == nums.length
1 <= n <= 300
nums[i]
进阶:
Language: JavaScript
/** * @param {number[]} nums * @return {void} * */ // 遇到0,把0放在数组最前方,此时i位置没变,不用处理 // 遇到2,把2放在数组最后放,此时i向后偏移了1,需要进行i--,然后数组末尾的2已经被统计过了,所以len可以对应再减1,避免重复的问题 var sortColors = function(nums) { let len = nums.length for (let i = 0; i < len; i++) { if (nums[i] === 0) { nums.splice(i, 1) nums.unshift(0) } else if (nums[i] === 2) { nums.splice(i, 1) nums.push(2) len-- i-- } } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
75. 颜色分类
Description
Difficulty: 中等
Related Topics: 数组, 双指针, 排序
给定一个包含红色、白色和蓝色、共
n
个元素的数组nums
,对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。我们使用整数
0
、1
和2
分别表示红色、白色和蓝色。必须在不使用库的sort函数的情况下解决这个问题。
示例 1:
示例 2:
提示:
n == nums.length
1 <= n <= 300
nums[i]
为0
、1
或2
进阶:
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: