【Leetcode】Sort Colors
来源:互联网 发布:aa租车 摇到号 知乎 编辑:程序博客网 时间:2024/05/17 11:04
题目链接:https://leetcode.com/problems/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.
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?
思路:
two pass的方法简单,one pass的方法参考别人的题解就http://fisherlei.blogspot.com/2013/01/leetcode-sort-colors.html
考虑到题目要求one pass。这就意味着类似于链表的双指针问题,这里也要track两个index,一个是red的index,一个是blue的index,两边往中间走。
i从0到blue index扫描,
遇到0,放在red index位置,red index后移;
遇到2,放在blue index位置,blue index前移;
遇到1,i后移。
扫描一遍得到排好序的数组。时间O(n),空间O(1),
算法1:
public void sortColors(int[] nums) {int c0 = 0,c1=0;for (int i = 0; i < nums.length; i++) {if(nums[i]==0)c0++;if(nums[i]==1)c1++;}for (int i = 0; i <c0; i++) {nums[i]=0;}for (int i = c0; i <(c0+c1); i++) {nums[i]=1;}for (int i = c0+c1; i <nums.length; i++) {nums[i]=2;}}
算法2:
int c0 = 0, c2 = nums.length - 1;for (int i = 0; i <= c2;) {if (nums[i] == 0) {nums[i] = nums[c0];nums[c0] = 0;c0++;i++;//必须要往前移一个,防止当第一个元素为0时陷入死循环} else if (nums[i] == 2) {nums[i] = nums[c2];nums[c2] = 2;c2--;//i不能++,防止当nums[c2]和nums[i]都为2发生错误}else{i++;}}
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- LeetCode 6 : ZigZag Conversion (Java)
- (七十二)while循环
- AngularJS实战第一章
- 《Android群英传》第一章~第二章
- 决策树归纳 基本概念
- 【Leetcode】Sort Colors
- (七十三)延迟循环、时钟单位、clock()
- 10016---jQuery--CSS类
- python基础教程共60课-第10课变量2
- OpenJudge_P4977 怪盗基德的滑翔翼(DP)
- Android API Guides 笔记
- Storyboard要点与技巧
- ZYB's Premutation POJ5592
- NYOJ 242 计算球体积