博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Color Sort
阅读量:4659 次
发布时间:2019-06-09

本文共 1960 字,大约阅读时间需要 6 分钟。

问题描述

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. 

 

解决思路

1. 计数排序;

2. 双指针法,一遍扫描;

 

程序

1. 普通版本

public class Solution {    public void sortColors(int[] nums) {        if (nums == null || nums.length == 0) {            return ;        }        int begin = 0, end = nums.length - 1;        while (true) {            while (begin < end && nums[begin] == 0) {                ++begin;            }            while (end > begin && nums[end] == 2) {                --end;            }            if (begin >= end) {                break ;            }            int p = end;            while (p >= begin && nums[p] == 1) {                --p;            }            if (p < begin) {                break;            }            if (nums[p] == 0) {                swap(nums, p, begin);            } else {                swap(nums, p, end);            }        }    }        private void swap(int[] nums, int i, int j) {        int tmp = nums[i];        nums[i] = nums[j];        nums[j] = tmp;    }}

2. 精炼版本

public class Solution {    public void sortColors(int[] nums) {        if (nums == null || nums.length == 0) {            return ;        }        int begin = 0, end = nums.length;        for (int i = 0; i < end; i++) {            if (nums[i] == 0) {                swap(nums, i, begin);                ++begin;            } else if (nums[i] == 2) {                --end;                swap(nums, i, end);                --i; // 交换前面的元素不确定为0或者1            }        }    }        private void swap(int[] nums, int i, int j) {        int tmp = nums[i];        nums[i] = nums[j];        nums[j] = tmp;    }}

  

转载于:https://www.cnblogs.com/harrygogo/p/4685014.html

你可能感兴趣的文章
wpf log4net使用
查看>>
python之路,正则表达式
查看>>
eclipse中java项目的创建
查看>>
Linux命令
查看>>
浅谈几种主要编程语言
查看>>
Linux tcpdump命令详解
查看>>
两个datagrid的数据移动(支持多选)
查看>>
HDU4826 Labyrinth
查看>>
jquery-layer
查看>>
JavaScript 基础
查看>>
iOS学习之六种传值方式
查看>>
EF 外键不显示、如何让外键显示!增、删、改 操作时,外键不显示,只显示导航属性!...
查看>>
mysql数据库数据恢复方案概括总结
查看>>
基于注解的spring3.0.x MVC学习笔记(二)
查看>>
算法入门经典-第五章 例题5-4 反片语
查看>>
PHP PSR-2 代码风格规范 (中文版)
查看>>
Python面向对象编程
查看>>
经典算法详解(12)分解质因数
查看>>
hbase namespace问题
查看>>
ui事件
查看>>