zoukankan      html  css  js  c++  java
  • [LeetCode] Sort Colors

    The hints on below the problem have suggested a two-pass solution.

    Now I will focus on the one-pass solution.

    The one-pass solution has no mystery. Just swap all 0's to the left and all 2's to the right and the 1's will automatically fall in the middle.

    Now comes the following code. You may play with it using some examples on a paper to see how it works.

    1     void sortColors(vector<int>& nums) {
    2         int red = 0, blue = nums.size() - 1;
    3         for (int i = 0; i <= blue; i++) {
    4             while (nums[i] == 2 && i < blue)
    5                 swap(nums[i], nums[blue--]);
    6             while (nums[i] == 0 && i > red)
    7                 swap(nums[i], nums[red++]);
    8         }
    9     }
  • 相关阅读:
    141. 环形链表
    15. 三数之和
    剑指 Offer 59
    177. 第N高的薪水
    176. 第二高的薪水
    175. 组合两个表
    剑指 Offer 57
    剑指 Offer 56
    110. 平衡二叉树
    置顶
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4563480.html
Copyright © 2011-2022 走看看