[LeetCode]Sort Colors
来源:互联网 发布:服务器端口安全策略 编辑:程序博客网 时间:2024/06/05 03:27
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:
思路2:模拟快排,将2和0分别移动到两边,这只需要遍历一次数组即可,算法复杂度O(N)
代码2:
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.
思路1:直接遍历数组统计三种颜色的个数然后依次填充,复杂度O(N)
代码1:
public void sortColors1(int[] A) {//统计1,2,3的个数 int [] colorCount = new int[3]; for(int i =0; i < A.length; ++i){ switch (A[i]){ case 0: colorCount[0] ++; break; case 1: colorCount[1] ++; break; case 2: colorCount[2] ++; break; } } int from, i = 0, to = 0; while (i < colorCount.length){ from = to; to = to + colorCount[i]; Arrays.fill(A, from ,to,i); i ++; } }
思路2:模拟快排,将2和0分别移动到两边,这只需要遍历一次数组即可,算法复杂度O(N)
代码2:
public void sortColors(int[] A) {//用快速排序的思想, final int RED = 0, WHITE = 1, BLUE = 2; int l =0, r = A.length - 1,mid = l; while (mid <= r){ if(A[mid] == RED){ int temp = A[mid]; A[mid] = A[l]; A[l] = temp; l ++; mid ++; }else if(A[mid] == BLUE){ int temp = A[mid]; A[mid] = A[r]; A[r] = temp; r --; }else { mid ++; } } }
1 0
- 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
- 我的大学(二)
- dfdsfdsf
- Preference的 相关类 及 常用方法
- 网络层学习笔记
- 安装Ubuntu 14.04后要做的5件事情
- [LeetCode]Sort Colors
- hdu5200 Trees( two points)
- NullPointerException是空指针异常
- 图像处理---关于像素坐标矩阵变换(平移,旋转,缩放,错切)
- UIView半透明悬浮效果
- hdu3388 Coprime【容斥原理】
- android使用Font Awesome字体图标
- sdut2168--Mathmen(贪心)
- nginx禁止访问某些后缀的文件