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.
Note:
You are not suppose to use the library’s sort function for this problem.
题意:
给定一个包含红,白,蓝且长度为n的数组,将数组元素进行分类使同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
用整数0,1和2分别代表红,白,蓝。
思路:
方法一:
利用计数排序,分别用三个变量countRed、countWhilte、countBlue来记录三种颜色各有几个。
1 | void sortColors(vector<int>& nums) { |
方法二:
自己实现快速排序。
1 | //1、获取中点值,划分块 |
方法三:
利用三个指针low、mid、heigh,通过移动三个指针和交换指针所指向元素的值,low指针左边都保证是0(红色),low指针和mid指针之间保证是1(白色),heigh指针右面都保证是2(蓝色)。
1 | void sortColors(vector<int> &nums) { |
Java Code
1 | class Solution { |
1 | class Solution { |