zoukankan      html  css  js  c++  java
  • 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.

     

    思路:使用两个int变量,这里我命名为left和right (或slow和fast)。这两个变量其实相当于两个指针,初始时都为0,即指向nums数组中下标为0的数。

    之后,right负责向右扫描一次nums数组。这次扫描的目的是把数组中所有的0都移到数组前端。

    具体扫描的规则是,right从0开始,判断当前下标中的数是否为0,若是则与left所指向位置的数交换,然后left加一;若不为0,则跳过这个数。

    经过一次循环后,我们再将所有的1都移到0后面。注意,经过前一次扫描后,left所指的下标正好是数组里所有0后面的第一个位置。

    此时令right=left,继续扫描,扫描规则和上次类似,不过这次是判断是否为1。扫描结束后算法结束,所有的2也已自动到了数组的最右。

    整个算法的时间复杂度为O(n),空间复杂度为O(1)。

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

     

  • 相关阅读:
    我的vimrc设置
    nginx
    选中
    vscode垂直选中列选中
    lsof
    bashrc和bash_profile
    centos安装tree命令
    linux查看磁盘大小df命令
    linux查看文件夹大小du命令
    git本地推送远程
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4906297.html
Copyright © 2011-2022 走看看