zoukankan      html  css  js  c++  java
  • LeetCode75 Sort Colors

    题目:

    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.

    Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

    Note:
    You are not suppose to use the library's sort function for this problem. (Medium)

    分析:

    最直观的想法就是遍历一遍数个数,再遍历一遍按照0,1,2的个数赋值。但题目的follow-up中也提出了不要这么做。

    一次遍历常数空间的算法就是采用双指针,模拟快排的思路移动元素。

    p1左侧表示0(如果有),p2右侧表示2(如果有)。

    这样一次遍历:

    遇到0,则swap(nums[i], nums[p1]) p1++

    遇到2,则swap(nums[i], nums[p2])p2--, 并且再判定一次i位置

    遇到1则 不操作。

    代码:

     1 class Solution {
     2 public:
     3     void sortColors(vector<int>& nums) {
     4         int p1 = 0, p2 = nums.size() - 1;
     5         for (int i = 0; i <= p2; ++i) {
     6             if (nums[i] == 0) {
     7                 swap(nums[i], nums[p1]);
     8                 p1++;
     9             }
    10             else if (nums[i] == 2) {
    11                 swap(nums[i], nums[p2]);
    12                 p2--;
    13                 i--;
    14             }
    15         }
    16         return;
    17     }
    18 };

     

     
  • 相关阅读:
    兰迪·波许教授的最后一课
    How can I convert from GdiPlus::Image to CBitmap?
    环境变量以及ControlSet
    判断操作系统类型的多种方法
    顺序表
    操作系统版本号
    64bit操作系统的重定向
    CListCtrl资料
    Custom draw 和 Owner draw 的区别
    Silent Install / Uninstall
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5914828.html
Copyright © 2011-2022 走看看