Lintcode 148 Sort Colors (双指针好题)

148 · Sort Colors

Description

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

You are not suppose to use the library's sort function for this problem.

You should do it in-place (sort numbers in the original array).

You are not allowed to use counting sort to solve this problem.

Example 1

Input : [1, 0, 1, 2]

Output : [0, 1, 1, 2]

Explanation : sort it in-place

Challenge

Could you come up with an one-pass algorithm using only O(1) space?

Show Hint

Related Knowledge

学习《算法------双指针思想》课程中的2.8双指针思想练习2相关内容 ,了解更多相关知识!

Tags

Related Problems

507

Wiggle Sort II

Hard

39

Recover Rotated Sorted Array

Easy

143

Sort Colors II

Medium

508

Wiggle Sort

Medium

625

Partition Array II

Medium

解法1:双指针

cpp 复制代码
class Solution {
public:
    /**
     * @param nums: A list of integer which is 0, 1 or 2
     * @return: nothing
     */
    void sortColors(vector<int> &nums) {
        int n = nums.size();
        //RED 0, WHITE 1, BLUE 2
        //Before each iteration in white loop:
        //  [0..red) are red 0
        //  [red..index) are white 1
        //  [index..blue] are unknown
        //  (blue..n-1] are blue 2
        int red = 0, index = 0, blue = n - 1;
        while (index <= blue) {  //注意:这里不是index<n!!!
            if (nums[index] == 0) {
                swap(nums[red], nums[index]); //nums[red]已经扫描过,一定是1,所以可以动index
                red++; index++;
            } else if (nums[index] == 1) {
                index++;
            } else { //nums[index] == 2
                swap(nums[blue], nums[index]); //nums[blue]还没有扫描过,可能是0,1,2,所以不能动index
                blue--;
            }
        }
        return;
    }
};
相关推荐
帅小伙―苏2 小时前
力扣42接雨水
前端·算法·leetcode
6Hzlia2 小时前
【Hot 100 刷题计划】 LeetCode 287. 寻找重复数 | C++ 数组判环 (快慢指针终极解法)
c++·算法·leetcode
穿条秋裤到处跑7 小时前
每日一道leetcode(2026.04.19):下标对中的最大距离
算法·leetcode·职场和发展
木子墨5168 小时前
LeetCode 热题 100 精讲 | 计算几何篇:点积叉积 · 线段相交 · 凸包 · 多边形面积
c++·算法·leetcode·职场和发展·动态规划
py有趣8 小时前
力扣热门100题之最小路径和
算法·leetcode
im_AMBER9 小时前
Leetcode 159 无重复字符的最长子串 | 长度最小的子数组
javascript·数据结构·学习·算法·leetcode
郝学胜-神的一滴9 小时前
[力扣 105]二叉树前中后序遍历精讲:原理、实现与二叉树还原
数据结构·c++·算法·leetcode·职场和发展
sheeta19989 小时前
LeetCode 每日一题笔记 日期:2026.04.20 题目:2078.两栋颜色不同而距离最远的房子
笔记·算法·leetcode
承渊政道9 小时前
【递归、搜索与回溯算法】(floodfill算法:从不会做矩阵题,到真正掌握搜索扩散思想)
数据结构·c++·算法·leetcode·矩阵·dfs·bfs
剑挑星河月10 小时前
73.矩阵置零
数据结构·算法·leetcode·矩阵