zoukankan      html  css  js  c++  java
  • [leetcode.com]算法题目

    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.

    click to show follow up.

    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 an one-pass algorithm using only constant space?

     1 class Solution {
     2 public:
     3     void swap(int &a, int &b){
     4         int temp = a;
     5         a = b;
     6         b = temp;
     7     }
     8     void sortColors(int A[], int n) {
     9         // Start typing your C/C++ solution below
    10         // DO NOT write int main() function
    11         if (n<2) return;
    12         
    13         int first = 0;
    14         int last = n-1;
    15         while(first<n && 0==A[first])
    16             first++;
    17         while(last>=0 && 2==A[last])
    18             last--;
    19             
    20         int i=first;
    21         while(first < last && i<=last){
    22             if (2==A[i]){
    23                 swap(A[i],A[last]);
    24                 last--;
    25                 while(last>=0 && 2==A[last])
    26                     last--;
    27             }else if(0==A[i]){
    28                 swap(A[i],A[first]);
    29                 first++;
    30                 if(i<first) i=first;
    31                 while(first<n && 0==A[first])
    32                     first++;
    33             }else{
    34                 i++;
    35             }
    36         }
    37     }
    38 };
    我的答案

    思路:如果只需要一次遍历,就地排序,其实在循环到每个数的时候要比两次遍历多做一些事情。因为0肯定是排在前面的,2肯定是排在后面的,指定两个指针,分别指向数组的两头,然后往中间缩进,注意分别讨论遍历到0,1,2时应该做何种运算,何种操作即可。

  • 相关阅读:
    常建的性能指标
    性能测试常见分类
    性能测试相关概念和指标
    adb命令熟悉
    打包ajax生成小工具
    深入理解类加载demo
    设计模式七大原则
    javamail邮件实现
    @RequiredArgsConstructor用法
    spring-security查询数据库源码解析
  • 原文地址:https://www.cnblogs.com/xuning/p/3337685.html
Copyright © 2011-2022 走看看