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;
    }
};
相关推荐
bestadc1 小时前
LeetCode 几道 Promises 和 Time 的题目
javascript·算法·leetcode
墨染点香1 小时前
LeetCode 刷题【71. 简化路径】
算法·leetcode·职场和发展
名誉寒冰2 小时前
LeetCode 24 两两交换链表中的节点( 迭代与递归)
算法·leetcode·链表
小欣加油2 小时前
leetcode LCR 170.交易逆序对的总数
数据结构·c++·算法·leetcode·职场和发展·排序算法
木尼1232 小时前
leedcode 算法刷题第三十一天
算法·leetcode·职场和发展
兴科Sinco3 小时前
[leetcode 1]给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数[力扣]
python·算法·leetcode
薛定谔的算法3 小时前
JavaScript单链表实现详解:从基础到实践
数据结构·算法·leetcode
元亓亓亓7 小时前
LeetCode热题100--230. 二叉搜索树中第 K 小的元素--中等
算法·leetcode·职场和发展
草莓熊Lotso7 小时前
《算法闯关指南:优选算法-双指针》--01移动零,02复写零
c语言·c++·经验分享·算法·leetcode
小欣加油15 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展