您的位置:首页 > 编程语言 > Java开发

leetcode:Sort Colors 【Java】

2016-03-04 10:04 465 查看
一、问题描述

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.
二、问题分析

利用两个计数器,红球计数器从前往后走,蓝球计数器从后往前走。

三、算法代码

public class Solution {
    public void sortColors(int[] nums) {
        int red = 0;
        int blue = nums.length - 1;
        int tmp = -1;
        for(int i = 0; i < blue + 1; ){
        	if(nums[i] == 0){
        		tmp = nums[red];
        		nums[red] = nums[i];
        		nums[i] = tmp;
        		red++;
        		i++;
        	}else if(nums[i] == 2){
        		tmp = nums[i];
        		nums[i] = nums[blue]; //当找到蓝球时,计数器i值要保持不变
        		nums[blue] = tmp;
        		blue--;
        	}else{
        		i++;
        	}
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: