p75

LeetCode 75 Contains Duplicate 题解

1.题目:

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.进行排序。

2.解题思路:

桶排序

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 

public class Solution {
public void sortColors(int[] nums) {
int[] ans = new int[3];
for (int i=0;i<nums.length;i++)
{
ans[nums[i]]++;
}
int j=0;
for (int i=0;i<nums.length;i++){
while (ans[j]==0) j++;
nums[i]=j;
ans[j]--;
}
}
}


4.一些总结: