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;
    }
};
相关推荐
GalaxyPokemon1 小时前
LeetCode - 76. 最小覆盖子串
运维·服务器·数据结构·算法·leetcode
蒟蒻小袁4 小时前
力扣面试150题--实现Trie(前缀树)
leetcode·面试·c#
大白曾是少年4 小时前
哈希表三种数据结构在leetcode中的使用情况分析
数据结构·leetcode·散列表
TGB-Earnest14 小时前
【leetcode-合并两个有序链表】
javascript·leetcode·链表
GEEK零零七14 小时前
Leetcode 3299. 连续子序列的和
算法·leetcode·动态规划
蒟蒻小袁14 小时前
力扣面试150题--单词接龙
算法·leetcode·面试
玉米的玉*」*17 小时前
【每日likou】704. 二分查找 27. 移除元素 977.有序数组的平方
数据结构·算法·leetcode
1白天的黑夜11 天前
二叉树-226.翻转链表-力扣(LeetCode)
数据结构·c++·leetcode
编程绿豆侠1 天前
力扣HOT100之贪心算法:45. 跳跃游戏 II
leetcode·游戏·贪心算法
黑听人1 天前
【力扣 中等 C++】90. 子集 II
开发语言·数据结构·c++·算法·leetcode