关闭

Sorts Colors

标签: 计数排序
118人阅读 评论(0) 收藏 举报
分类:

题目描述

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.

题目解答

解题思路

  • 先统计red , white, blue 三组颜色的个数,然后分别按照颜色的个数建立数组
  • 双指针法

代码实现

  • 计数排序
public class Solution {
    public void sortColors(int[] nums) {
        if(nums == null || nums.length == 0)
            return ;
        int redCount = 0, whiteCount = 0, blueCount = 0;
        for(int i = 0; i < nums.length; i++){
            switch(nums[i]){
                //红色
                case 0:
                    redCount++;
                    break;
                case 1:
                    whiteCount++;
                    break;
                case 2:
                    blueCount++;
                    break;
                default:
            }
        }
        for(int i = 0; i < nums.length; i++){
            if(redCount > 0){
                nums[i] = 0;
                redCount--;
            }else if(whiteCount > 0){
                nums[i] = 1;
                whiteCount--;
            }else {
                nums[i] = 2;
            }
        }
    }
}

双指针法

public class Solution {
    /**
      *双指针 一个redPos, 一个bluePos
      */
    public void sortColors(int[] nums) {
       if(nums == null || nums.length == 0)
            return ;

        int redPos = 0, bluePos = nums.length-1;
        int i = 0;
        while(i <= bluePos){
            if(nums[i] == 0){
                //0交换回来的只能是1 所以直接加
                swap(nums, redPos, i);
                redPos++;
            }else if(nums[i] == 2){
                //2交换回来的可能是0 所以要继续判断
                swap(nums, bluePos, i);
                bluePos--;
                continue;
            }

            i++;
        }
    }

    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:39528次
    • 积分:1840
    • 等级:
    • 排名:千里之外
    • 原创:148篇
    • 转载:1篇
    • 译文:0篇
    • 评论:1条
    博客专栏
    最新评论