Sorts Colors

来源:互联网 发布:2016 mac pro强制重启 编辑:程序博客网 时间:2024/06/05 23:52

题目描述

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
原创粉丝点击