Sort Colors
leetcode75
题目:
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?
思路:题意即数组中只存储3种数字0,1,2,要求在 O(1) 空间复杂度的情况下,最好只遍历 1 次数组。
题目给出了遍历2次数组的做法:计数排序
计数排序
public void CountSort(int[] nums){
int n0 = 0, n1 = 0, n2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) n0++;
else if (nums[i] == 1) n1++;
else if (nums[i] == 2) n2++;
}
int i = 0;
while(n0-- > 0) nums[i++] = 0;
while(n1-- > 0) nums[i++] = 1;
while(n2-- > 0) nums[i++] = 2;
}
想到1次遍历过程,容易想到双指针的方法。遍历到0交换到前面得到一个0或1,遍历到2交换到后面得到一个未知数,因此要继续遍历这个交换过来的数。遍历到right,即后面都为2,遍历结束。
双指针遍历
public void sortColors(int[] nums){
if (nums.length <= 1) return;
int left = 0, right = nums.length - 1;
for (int i = 0; i <= right ; i++) {
if (nums[i] == 0) {
swap(nums, i, left++);
} else if (nums[i] == 2) {
swap(nums, i--, right--);
}
}
}
public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
考虑不使用双指针直接在原数组上修改的方法。维护0,1,2应该写入的位置。每次遍历一次就写入一个2,遍历结果为1就补写一个1,遍历结果为0就补写一个0,并让1应写入的位置增加1个单位即可。事实上,这种方法的优点在于,当知道数组仅由n个有限值构成时,此方法依然奏效。
遍历改写
public void sortColors(int[] nums){
if (nums.length <= 1) return;
int n0 = -1, n1 = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0){
nums[i] = 2;
nums[++n1] = 1;
nums[++n0] = 0;
}else if (nums[i] == 1){
nums[i] = 2;
nums[++n1] = 1;
}else if (nums[i] == 2){
nums[i] = 2;
}
}
}

341

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



