leetcode数组专项习题:颜色排序

版权声明:本文为博主原创,未经允许请不要转载哦 https://blog.csdn.net/weixin_43277507/article/details/88104525

8、颜色排序
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?
题设要求:给定一个具有红色,白色或蓝色的n个对象的数组,对它们进行排序,使相同颜色的对象相邻,颜色顺序为红色,白色和蓝色。这里,我们将使用整数0,1和2分别表示红色,白色和蓝色。
注意:不能使用库的排序功能来解决此问题。
一个相当直接的解决方案是使用计数排序的两遍算法。
首先,迭代0,1,和2的数组计数,然后覆盖总数为0的数组,然后是1,然后是2。
你能想出一个只使用恒定空间的一次通过算法吗?
代码:

public class Solution{
    public static void main(String[] args) {
    	Solution sl = new Solution();
        int[] A= {0};
        sl.sortColors(A);
        int len=A.length;
        for(int i=0;i<len;i++)
        {
        	System.out.print(A[i]);
        }
    }
    public void sortColors(int[] A)
    {
        //不能使用排序算法
    	int len=A.length;
    	int red=0;
    	int white=0;
    	int blue=0;
    	for (int i=0;i<len;i++)
    	{
    		if(A[i]==0)
    		{
    			red++;
    		}
    		if(A[i]==1)
    		{
    			white++;
    		}
    		
    		if(A[i]==2)
    		{
    			blue++;
    		}
    		
    	}
    	for(int i=0;i<red;i++)
    	{
    	   A[i]=0;
    	}
    	for(int i=red;i<white+red;i++)
    	{
    		A[i]=1;
    	}
    	for(int i=white+red;i<len;i++)
    	{
    		A[i]=2;
    	}  	
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88104525