LeetCode-Sort Colors
来源:互联网 发布:北京纸箱厂 淘宝定做 编辑:程序博客网 时间:2024/04/27 22:36
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.
brute force的方法就是一遍把三种颜色都数一遍, 然后再一遍一个一个赋值。走一遍的方法就是两个指针,一个在前面指排好的0的末尾,另一个在后面指排好的2的最前面,只要是遇到0 2 就swap,1就不用管。注意要用while,就是可能换过来的那个数字也要继续swap。同时两个while的先后顺序是有关系的,要先处理好2的情况,再swap所有0的情况。因为有可能从后面swap 2的时候,换过来一个0,但是不可能swap 0的时候从前面换过来一个2.因为current指的位置之前只可能有0和1.
public class Solution { public void sortColors(int[] A) { if (A ==null || A.length == 0) return; int first = 0; int last = A.length -1; for ( int i = 0; i <= last; i ++){ while ( A[i] == 2 && i < last){ int temp = A[i]; A[i] = A[last]; A[last] = temp; last --; } while ( A[i] == 0 && i > first){ int temp = A[i]; A[i] = A[first]; A[first] = temp; first ++; } } }}还有一个解法没仔细研究 感觉不太好想。
void sortColors(int A[], int n) { int n0 = -1, n1 = -1, n2 = -1; for (int i = 0; i < n; ++i) { if (A[i] == 0) { A[++n2] = 2; A[++n1] = 1; A[++n0] = 0; } else if (A[i] == 1) { A[++n2] = 2; A[++n1] = 1; } else if (A[i] == 2) { A[++n2] = 2; } }}
0 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
- Deep Learning(深度学习)学习笔记整理系列之LeNet-5卷积参数个人理解
- 日经社説 20150331 普天間移設を法廷で争うのは筋違いだ
- tomcat(错误二) tomcat端口被占用了的解决办法
- JS中的prototype
- C# 对文本文件的几种读写方法总结
- LeetCode-Sort Colors
- VisionMobile:开发者经济报告 2015年Q1:开发者国度状况(四)应用经济收入分化
- 社説 20150331 生活困窮者支援 早期の対応で自立を促したい
- Linux 图片转换命令 convert
- android软件版本升级时,安装新版本后,没有出现安装成功界面或直接回到桌面
- MFC 父窗口和子窗口之间传值
- Android中的setLayoutParams是给父控件看的
- mysql 数据库 varchar 到底可以存多少数据呢,长文慎入
- 依赖倒置原则