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;
    }
};
相关推荐
醉颜凉19 分钟前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐21 分钟前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗22 分钟前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
User_芊芊君子22 分钟前
【LeetCode经典题解】搞定二叉树最近公共祖先:递归法+栈存路径法,附代码实现
算法·leetcode·职场和发展
培风图南以星河揽胜22 分钟前
Java版LeetCode热题100之零钱兑换:动态规划经典问题深度解析
java·leetcode·动态规划
算法_小学生23 分钟前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
执着25923 分钟前
力扣hot100 - 234、回文链表
算法·leetcode·链表
熬夜造bug25 分钟前
LeetCode Hot100 刷题路线(Python版)
算法·leetcode·职场和发展
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #108:将有序数组转换为二叉搜索树(递归分治、迭代法等多种实现方案详解)
算法·leetcode·二叉树·二叉搜索树·平衡树·分治法
踩坑记录1 小时前
leetcode hot100 104. 二叉树的最大深度 easy 递归dfs 层序遍历bfs
leetcode·深度优先·宽度优先