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.
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 an one-pass algorithm using only constant space?
题意:给出由0,1,2三个数组成的数组,要求用时间复杂度为O(n),空间复杂度为O(1)
思路:分别从两边搜索,从左边找到第一个不为0的位置,从右边找到第一个不为2的位置,然后从这两个位置开始查找,如果为0,将其与左边的数替换,如果为2,将其与右边的数替换
代码如下:
public class Solution {
public void sortColors(int[] nums) {
int left = 0, right = nums.length - 1;
while (left <= right && nums[left] == 0) left++;
while (right >= 0 && nums[right] == 2) right--;
if (left >= right) return;
int tmp;
int a = left;
while (a <= right) {
if (nums[a] == 0) {
tmp = nums[a];
nums[a] = nums[left];
nums[left] = tmp;
a++;
left++;
} else if (nums[a] == 2) {
tmp = nums[right];
nums[right] = nums[a];
nums[a] = tmp;
while (nums[right] == 2) right--;
if (nums[a] == 1) a++;
} else a++;
}
}
}
本文介绍了一种使用常空间复杂度O(1)和时间复杂度O(n)的算法来解决数组中颜色排序的问题。通过从数组两端分别搜索不同颜色的位置并进行交换,实现数组元素按颜色顺序排列。

3157

被折叠的 条评论
为什么被折叠?



