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

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

题目:

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?

 

题解:

这道题就是运用指针来解决了,可以说叫3指针吧。

一个指针notred从左开始找,指向第一个不是0(红色)的位置;一个指针notblue从右开始往左找,指向第一个不是2(蓝色)的位置。

然后另一个新的指针i指向notred指向的位置,往后遍历,遍历到notred的位置。

这途中需要判断:

当i指向的位置等于0的时候,说明是红色,把他交换到notred指向的位置,然后notred++,i++。

当i指向的位置等于2的时候,说明是蓝色,把他交换到notblue指向的位置,然后notred--。

当i指向的位置等于1的时候,说明是白色,不需要交换,i++即可。

 

代码如下:

 1     
public 
static 
void swap(
int A[], 
int i, 
int j){
 2         
int tmp = A[i];
 3         A[i]=A[j];
 4         A[j]=tmp;
 5     }
 6     
 7     
public 
static 
void sortColors(
int A[]) {
 8         
if(A == 
null || A.length==0)
 9             
return;
10             
11         
int notred=0;
12         
int notblue=A.length-1;
13          
14         
while (notred<A.length&&A[notred]==0)
15             notred++;
16             
17         
while (notblue>=0&&A[notblue]==2)
18             notblue--;
19          
20         
int i=notred;
21         
while (i<=notblue){
22             
if (A[i]==0) {
23                 swap(A,i,notred);
24                 notred++;
25                 i++;
26             }
else 
if (A[i]==2) {
27                 swap(A,i,notblue);
28                 notblue--;
29             }
else
30                 i++;
31         }
32     }

 

 

转载地址:http://mcpml.baihongyu.com/

你可能感兴趣的文章
Ant Design源码分析(三):Wave组件
查看>>
91. Decode Ways
查看>>
宜信 | 供应链金融+区块链双链合璧
查看>>
JS每日一题: 请简述一下vuex实现原理
查看>>
leetcode409.Longest Palindrome
查看>>
将军令:数据安全平台建设实践
查看>>
JavaScript原型与构造函数笔记
查看>>
220. Contains Duplicate III
查看>>
LeetCode36.有效的数独 JavaScript
查看>>
表单密码自动填充hack
查看>>
从零开始的无人驾驶 1
查看>>
DevOps自动化工具集合
查看>>
Android平台架构的介绍和源码下载
查看>>
前端 CSS : 5# 纯 CSS 实现24小时超市
查看>>
Linux中用户管理
查看>>
【译】为什么我更喜欢对象而不是switch语句
查看>>
上线清单 —— 20 个 Laravel 应用性能优化项
查看>>
浅谈React Hooks
查看>>
SpiderData 2019年2月27日 DApp数据排行榜
查看>>
linux mpstat命令
查看>>