版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/87631443
Description:
Given an array with n objects colored red, white or blue, sort them in-place 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.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
- A rather straight forward solution is a two-pass algorithm using counting sort.
- First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.
- Could you come up with a one-pass algorithm using only constant space?
题意:用0,1,2分别表示红、绿、蓝三种颜色;现给定一个包含元素0,1,2的数组,要求对数组按照红、绿、蓝的顺序进行排序(即数组首部为元素0,中间为元素1,尾部为元素2);并且要求空间复杂度为O(1);
解法:假设此时我们要分类的元素只有两类,那么我们可以同时遍历数组的首尾部分进行交换(假设要排序的是元素0和1,那么将尾部的1交换到首部,将首部的0交换到尾部);同理,对于分类排序的元素有三类时,我们只要保证所有的0和2分别在首部和尾部即可,这样排序之后1自然而然的就处于中间位置;
Java
class Solution {
public void sortColors(int[] nums) {
int left = 0;
int right = nums.length - 1;
boolean changed = true;
while (changed) {
changed = false;
for (int i = left; i <= right; i++) {
if (nums[i] == 0) {
changed = true;
exchange(nums, left, i);
left++;
break;
}
}
for (int i = right; i >= left; i--) {
if (nums[i] == 2) {
changed = true;
exchange(nums, right, i);
right--;
break;
}
}
}
}
private void exchange(int[] nums, int pos1, int pos2) {
int temp = nums[pos1];
nums[pos1] = nums[pos2];
nums[pos2] = temp;
}
}