75 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.

Example :

Example: 0,2,1,0,2,2,1,0

Note: You are not suppose to use the library's sort function for this problem.

题目翻译

给定一个带有红色,白色或蓝色的n个对象的数组,对它们进行排序,使相同颜色的对象相邻,颜色顺序为红色,白色和蓝色。

在这里,我们将使用整数0,1和2分别表示红色,白色和蓝色。

示例:

示例: 0,2,1,0,2,2,1,0

*注意: 对于这个问题,不允许使用已有的排序库

解题方案

标签: Sort

代码:

public class Solution {
    public void swap(int[] A,int a,int b){
        int temp = A[a];
        A[a] = A[b];
        A[b] = temp;
    }

    public void sortColors(int [] nums){
        int length = nums.length;
        int i=0,r=0,b=0;
        for (i=0;i<length-b;i++){
            if (nums[i] == 0) {
                swap(nums, i, r);
                r++;
            } else if (nums[i] == 2) {
                swap(nums, i, length-1-b);
                b++;
                i--; 
            }
        }

    }
}
Author:张浩

results matching ""

    No results matching ""