zoukankan      html  css  js  c++  java
  • 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.

    就是把三种颜色相同的放在一起,0,1,2,代表三种颜色,按0,1,2排序。

    算法分析:其实就是数组排序的问题,但是数组元素只有三种,所以,可以采用快速排序的思想,设置两个指针,先把0颜色放在最左边,然后把1颜色放在次左边。

    也可以直接使用快速排序,只不过时间复杂度有点高,并且栈溢出。

    public class SortColors
    {
    	public static void sortColors(int[] nums)
    	{
            int start = 0;
            int end = nums.length - 1;
            while(start <= end)//把0都放在左边
            {
            	if(nums[start] != 0)
            	{
            		if(nums[end] == 0)
            		{
            			int temp = nums[start];
            			nums[start] = nums[end];
            			nums[end] = temp;
            			start ++;
            			end --;
            		}
            		else
            		{
            			end --;
            		}
            	}
            	else
            	{
            		start ++;
            	}
            }
            
            end = nums.length - 1;
            while(start <= end)//把1都放在左边
            {
            	if(nums[start] != 1)
            	{
            		if(nums[end] == 1)
            		{
            			int temp = nums[start];
            			nums[start] = nums[end];
            			nums[end] = temp;
            			start ++;
            			end --;
            		}
            		else
            		{
            			end --;
            		}
            	}
            	else
            	{
            		start ++;
            	}
            }
        }
    	
    	//快速排序
    	public static void sortColors2(int[] nums)
    	{
    		quickSort(nums, 0, nums.length - 1);
    	}
    	public static void quickSort(int[] nums, int left, int right)
    	{
    		int leftIndex = left;
    		int rightIndex = right;
    		int pivot = nums[(leftIndex + rightIndex)/2];
    		while(leftIndex <= rightIndex)
    		{
    			while(nums[leftIndex] < pivot)
    			{
    				leftIndex ++;
    			}
    			while(nums[rightIndex] > pivot)
    			{
    				rightIndex --;
    			}
    			if(leftIndex <= rightIndex)
    			{
    				int temp = nums[leftIndex];
    				nums[leftIndex] = nums[rightIndex];
    				nums[rightIndex] = temp;
    				leftIndex ++;
    				rightIndex --;
    			}
    			if(leftIndex < right)
    			{
    				quickSort(nums, leftIndex, right);
    			}
    			if(rightIndex > left)
    			{
    				quickSort(nums, left, rightIndex);
    			}
    		}
    	}
    }
    
  • 相关阅读:
    Scrapy数据持久化
    Mybatis源码与Spring源码中设计模式的应用总结
    Count-Min Sketch 算法
    加解密算法、消息摘要、消息认证技术、数字签名与公钥证书
    智能卡系统设计(一) 断电保护和数据备份
    TCP/IP协议——ARP详解
    DES算法详解
    Python调用外部程序——os.system()和subprocess.call()
    Python实现截图
    Linux笔记:SSH客户端断开配置
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5788389.html
Copyright © 2011-2022 走看看