LeetCode 热题 100_颜色分类(98_75_中等_C++)(技巧)(计数;双指针)
LeetCode 热题 100_颜色分类(98_75_中等_C++)
- 题目描述:
- 输入输出样例:
- 题解:
- 解题思路:
- 思路一(计数):
- 思路二(双指针):
- 代码实现
- 代码实现(思路一(计数)):
- 代码实现(思路二(双指针)):
- 以思路一为例进行调试
题目描述:
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 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] 为 0、1 或 2
题解:
解题思路:
思路一(计数):
1、分别对红、白、蓝进行计数,再对数组进行更改。
2、复杂度分析:
① 时间复杂度:O(n),n为数组中元素的个数,计数时遍历一遍数组,更改时遍历一遍数组。
② 空间复杂度:O(1)。
思路二(双指针):
1、具体思想:从左往右遍历数组,如果为0则放到左边,如果为2则放到右边。因在原数组进行变换所以使用swap。
- 使用left指针来标记所有0的区域。
- 使用right指针来标记所有2的区域。
- current指针遍历整个数组,将0、1、2放到正确的位置。
2、复杂度分析:
① 时间复杂度:O(n),n为数组中元素的个数,遍历一遍数组。
② 空间复杂度:O(1)。
代码实现
代码实现(思路一(计数)):
class Solution1 {
public:// sortColors函数:排序颜色问题,使用计数排序的方式void sortColors(vector<int> &nums) {int red = 0, white = 0; // red记录0的个数,white记录1的个数// 遍历nums数组,统计0和1的个数for(int &i : nums) {if (i == 0) { // 如果当前元素是0,增加red计数red++;} else if (i == 1) { // 如果当前元素是1,增加white计数white++;}}// 计算white的正确索引位置white = red + white; // white是1的最后一个位置的索引+1// 将数组中前red个元素设置为0for (int i = 0; i < red; i++) {nums[i] = 0;}// 将数组中red到white-1的元素设置为1for (int i = red; i < white; i++) {nums[i] = 1; }// 将数组中从white开始的位置设置为2for (int i = white; i < nums.size(); i++) {nums[i] = 2; }}
};
代码实现(思路二(双指针)):
class Solution2 {
public:void sortColors(vector<int>& nums) {int left = 0, right = nums.size() - 1, current = 0;// 使用三指针,分别控制0、1、2的位置while (current <= right) {if (nums[current] == 0) {// 0的情况,交换当前元素和left位置的元素swap(nums[left], nums[current]);left++;current++;} else if (nums[current] == 1) {// 1的情况,直接移动current指针current++;} else {// 2的情况,交换当前元素和right位置的元素swap(nums[current], nums[right]);right--;}}}
};
以思路一为例进行调试
#include<iostream>
#include<vector>
using namespace std;class Solution2 {
public:void sortColors(vector<int>& nums) {int left = 0, right = nums.size() - 1, current = 0;// 使用三指针,分别控制0、1、2的位置while (current <= right) {if (nums[current] == 0) {// 0的情况,交换当前元素和left位置的元素swap(nums[left], nums[current]);left++;current++;} else if (nums[current] == 1) {// 1的情况,直接移动current指针current++;} else {// 2的情况,交换当前元素和right位置的元素swap(nums[current], nums[right]);right--;}}}
};int main(int argc, char const *argv[])
{vector<int> nums={2,0,2,1,1,0};Solution2 s;s.sortColors(nums);for (int i = 0; i < nums.size(); i++){cout<<nums[i]<<" ";}return 0;
}
LeetCode 热题 100_颜色分类(98_75)原题链接
欢迎大家和我沟通交流(✿◠‿◠)