【LeetCode】 075. Sort Colors
来源:互联网 发布:金兰软件怎么样 编辑:程序博客网 时间:2024/05/22 05:00
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 start = 0, end = nums.length - 1; for (int i = 0; i <= end; i++) { while (nums[i] == 2 && i < end) { int temp = nums[i]; nums[i] = nums[end]; nums[end--] = temp; } while (nums[i] == 0 && i > start) { int temp = nums[i]; nums[i] = nums[start]; nums[start++] = temp; } } }}
0 0
- 【LeetCode】 075. Sort Colors
- 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
- wamp+win10: php连接Mysql, delete update insert 详细操作步骤
- Leetcode 332. Reconstruct Itinerary
- Eularian Path
- 火星人的真实故事,读后感言
- 计算机图形学-初入门(小作品)
- 【LeetCode】 075. Sort Colors
- 还要和师兄混
- mmw mimo系统预编码
- 7107小时时,加入创业公司(没有股份,当作经验吧)
- [Leetcode] 63. Unique Paths II 解题报告
- 你不知道的“虚假需求”
- 怎么发现愿景和目标 | 进击
- 2016年总结
- 火星人家园:火星人的真实故事(2)