• 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.

    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?

    Solution:

    应该用双指针,一个在头一个在尾,这样就可以分割数组。 头为red,故找个一个red,交换位置头指针++; 尾为blue,故找到一个blue,交换位置同时尾指针--。

     1 public class Solution {
     2     public void sortColors(int[] A) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int red = 0;
     6         int blue = A.length - 1;
     7         int i = 0;
     8         while(i <= blue){
     9             if(A[i] == 0){
    10                 A[i] = A[red];
    11                 A[red] = 0;
    12                 red ++;
    13                 i ++;
    14             }else if(A[i] == 2){
    15                 A[i] = A[blue];
    16                 A[blue] = 2;
    17                 blue --; 
    18             }else{
    19                 i ++;
    20             }
    21         }
    22     }
    23 }

     第三遍:

     1 public class Solution {
     2     public void sortColors(int[] A) {
     3         int red = 0, white = 0;
     4         if(A == null || A.length == 0) return;
     5         for(int i = 0; i <A.length; i ++){
     6             if(A[i] == 0) red ++;
     7             else if(A[i] == 1) white ++;
     8         }
     9         for(int i = 0; i < A.length; i ++){
    10             if(red > 0){
    11                 A[i] = 0;
    12                 red --;
    13             }else if(white > 0){
    14                 A[i] = 1;
    15                 white --;
    16             }else
    17                 A[i] = 2;
    18         }
    19     }
    20 }
  • 相关阅读:
    vscode里的NPM脚本
    Vue之生命周期activated与created使用
    分享10个超棒的设计素材网站
    使用node搭建静态资源服务器
    vue 动态组件的传值
    一文带你入门正则表达式
    一文告诉你git如何使用
    一文告诉你三种常见跨域解决方案
    一文告诉你原型与原型链是什么?
    一文告诉你 Event Loop 是什么?
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3348370.html
Copyright © 2020-2023  润新知