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

    Given an array with n objects colored red, white or blue, sort them in-place 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.

    Example:

    Input: [2,0,2,1,1,0]
    Output: [0,0,1,1,2,2]

    Follow up:

      • A rather straight forward solution is a two-pass algorithm using counting sort.
        First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
      • Could you come up with a one-pass algorithm using only constant space?

    题意

    给只包含0,1,2的数组排序

    题解

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

    感觉数算往年题看见过类似的题型,还是挺有趣的

    虽然我还是WA了好几遍过的

    狂赌之渊啥时候出熟肉啊,为啥生肉播放还不流畅x

  • 相关阅读:
    Pytorch 入门之Siamese网络
    Pytorch 之 backward
    非极大值抑制(NMS)
    Apriori 算法python实现
    canny 算子python实现
    转载
    ubuntu 安装lightgbm
    OneHotEncoder独热编码和 LabelEncoder标签编码
    Adroid—— DVM
    PHP——做服务
  • 原文地址:https://www.cnblogs.com/yalphait/p/10371765.html
Copyright © 2011-2022 走看看