LeetCode——Sort Colors

来源:互联网 发布:wemall商业版java源码 编辑:程序博客网 时间:2024/05/17 01:33

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.

Java代码

public class Solution {    public void sortColors(int[] A) {        int m =0;        int n =0;        int k =0;        for(int i =0;i<A.length;i++)            if(A[i]==0)                m++;            else if(A[i]==1)                n++;            else                k++;        for(int i=0;i<A.length;i++)            A[i] = i<m?0:i<(m+n)?1:2;    }}

上述代码通过。

题目中说,能否用一趟的算法,常数的存储空间实现?马上想到的是快排的左右分堆的方法,,,试了好久没试出来。。以后再想 

0 0