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

    将数组中的0,1,2分别排序,使得相同的数字相邻,这个比较简单,直接看代码:

     1 class Solution {
     2 public:
     3     void sortColors(vector<int>& nums) {
     4         int redNum = count(nums.begin(), nums.end(), 0);
     5         int whiteNum = count(nums.begin(), nums.end(), 1);
     6         int blueNum = count(nums.begin(), nums.end(), 2);
     7         int sz = nums.size();
     8         vector<int> ret(sz, 0);
     9         int redCount = 0, whiteCount = 0, blueCount = 0 ;
    10         for(int i = 0; i < sz; ++i){
    11             if(nums[i] == 0){
    12                 ret[redCount++] = 0;
    13             }else if(nums[i] == 1){
    14                 ret[whiteCount + redNum] = 1;
    15                 whiteCount++;
    16             }else{
    17                 ret[blueCount + redNum + whiteNum] = 2;
    18                 blueCount++;
    19             }
    20         }
    21         nums = ret;
    22     }
    23 };

     当时题目要求的事one-pass,const-space algorithm,当时硬是没想出来,现在看了下别人的解答,真简洁,原理很简单,3指针,画个图就能看懂了,代码如下所示:

     1 public class Solution {
     2     public void sortColors(int[] nums) {
     3         int i = 0;
     4         int j = nums.length - 1;
     5         int k = nums.length - 1;
     6         while(i <= j){
     7             if(nums[i] == 2){
     8                 int tmp = nums[k];
     9                 nums[k] = nums[i];
    10                 nums[i] = tmp;
    11                 k--;
    12                 if(k < j)
    13                     j = k;
    14             }else if(nums[i] == 1){
    15                 int tmp = nums[j];
    16                 nums[j] = nums[i];
    17                 nums[i] = tmp;
    18                 j--;
    19             }else{
    20                 i++;
    21             }
    22         }
    23     }
    24 }
  • 相关阅读:
    理解cookie和session机制
    http协议中connection头的作用
    [转]使用Wireshark来检测一次HTTP连接过程
    http协议学习系列
    xcode清空project list
    How To Use Git Source Control with Xcode in iOS 6
    iOS开发XCODE5 SVN配置 使用办法
    iOS申请证书,Certificates, Identifiers &Profiles 简介
    C#学习单向链表和接口 IList<T>
    halcon学习笔记——(7)HALCON标定后的二维测量
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4903631.html
Copyright © 2011-2022 走看看