博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【一天一道LeetCode】#75. Sort Colors
阅读量:4197 次
发布时间:2019-05-26

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

一天一道LeetCode

本系列文章已全部上传至我的github,地址:

欢迎大家关注我的新浪微博,
欢迎转载,转载请注明出处

(一)题目

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.

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?

(二)解题

题目大意:数组包含0,1,2,按照大小排列这些数字。

1、最简单的方法

利用STL的sort一句话就解决了。

class Solution {public:    void sortColors(vector
& nums) { sort(nums.begin(),nums.end()); }};

2、两个指针

算法思想很简单,把所有的0交换到队首,把所有的1交换到队尾

class Solution {public:    void sortColors(vector
& nums) { int start = 0; int end = nums.size()-1; for(int i = 0 ; i
=start ;i--)//把2交换到尾部 { if(nums[i]==2){ if(i!=end) swap(nums[i],nums[end]); end--; } } }};

3、两个指针优化版

维持三个指针i、j和k,从0~i表示1,i+1~j表示1,k~nums.size()表示2

代码也比较简单:

class Solution {public:    void sortColors(vector
& nums) { int i = 0, j = i, k = nums.size() - 1; while(j <= k){ if(nums[j] == 0) swap(nums[i++], nums[j++]);//0交换到前面 else if(nums[j] == 1) j++;//1保持不动 else swap(nums[k--], nums[j]);//2交换到尾部 } }};
你可能感兴趣的文章
配置spark令其支持hive
查看>>
调度工具:Airflow
查看>>
Mysql存储引擎比较
查看>>
微服务实践总结
查看>>
序列模式PrefixSpan算法介绍
查看>>
实时流处理Storm、Spark Streaming、Samza、Flink孰优孰劣
查看>>
Hbase centos下单机安装
查看>>
weblogic单机安装(centos/linux)
查看>>
Tomcat单机安装(centos/linux)
查看>>
SpringCloud分布式开发五大神兽
查看>>
Tableau 10.3 简单Dashboard创建
查看>>
IBM Cognos 11 简单Dashboard创建
查看>>
随想 110715
查看>>
Service
查看>>
构筑全栈式安全体系
查看>>
金橙子激光打标机的二次开发(C#)
查看>>
(坑集)virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not
查看>>
如何使用软碟通制作启动U盘
查看>>
Ubuntu16.04安装Python3.6
查看>>
Ubuntu apt-get和pip源更换以及apt update和upgrade 的区别
查看>>