leetcode75: Sort Colors

来源:互联网 发布:怎么自己开淘宝网店 编辑:程序博客网 时间:2024/06/07 01:45

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.

题目应该是需要你维护两个指针,通过交换的方式来排序。不过好像直接计数更容易

public void sortColors(int[] nums) {int red = 0;int white = 0;int blue = 0;for (int i = 0; i < nums.length; i++)if (nums[i] == 0)red++;else if (nums[i] == 1)white++;else if (nums[i] == 2)blue++;int k = 0;while (k < red) {nums[k] = 0;k++;}while (k < red + white) {nums[k] = 1;k++;}while (k < red + white + blue) {nums[k] = 1;k++;}}


原创粉丝点击