Leetcode no. 75
2016-05-06 10:32
323 查看
75. 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?
public class Solution {
public void sortColors(int[] nums) {
int left=0, right= nums.length-1;
for (int i = 0; i <= right; i++) {
if (nums[i]==0){
nums[i]= nums[left];
nums[left++]=0;
} else if (nums[i]== 2){
nums[i--]= nums[right];
nums[right--]= 2;
}
}
}
}
相关文章推荐
- iOS私有API的了解
- Fragment深入学习
- ASP.NET的事件模型
- Java虚拟机参数设置问题
- Django升级1.9.6出现的中文本地化bug
- C++连接mysql数据库的两种方法
- 设计模式C++学习笔记之九(Template Method模板方法模式)
- Orocos DataPort 解析: orocos lock free data object
- 关于 软中断
- 第十一周项目1-点-圆-圆柱类族的设计(1)
- c++第六次上机作业
- C++基础知识——变量存储位置
- [一起学Hive]之四-Hive的安装配置
- Freeform SQL (FFSQL) - Tip - How to create TEMP(Temporary) tables
- Postgresql 远程同步(非实时同步,小数据量)
- asp.net C#母版页和内容页事件排版加载顺序生命周期
- 如何查找UDID
- iOS 微信支付
- Codeforces 669D Little Artem and Dance (胡搞 + 脑洞)
- inside the c++ object