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;
    }
};
相关推荐
我搞slam1 小时前
插入区间--leetcode
算法·leetcode
前进之路91 小时前
Leetcode每日一练--40
算法·leetcode
Swift社区1 小时前
LeetCode 405 - 数字转换为十六进制数
算法·leetcode·职场和发展
py有趣3 小时前
LeetCode学习之0矩阵
学习·leetcode·矩阵
Q741_1474 小时前
C++ 分治 快速选择算法 堆排序 TopK问题 力扣 215. 数组中的第K个最大元素 题解 每日一题
c++·算法·leetcode·分治·1024程序员节·topk问题·快速选择算法
鱼儿也有烦恼4 小时前
快速学完 LeetCode top 1~50 [特殊字符]
java·算法·leetcode·1024程序员节
独自破碎E4 小时前
LeetCode 380: O(1) 时间插入、删除和获取随机元素
java·算法·leetcode
Swift社区5 小时前
LeetCode 406 - 根据身高重建队列
算法·leetcode·1024程序员节
爱coding的橙子15 小时前
每日算法刷题Day78:10.23:leetcode 一般树7道题,用时1h30min
算法·leetcode·深度优先
Swift社区15 小时前
LeetCode 403 - 青蛙过河
算法·leetcode·职场和发展