Description
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
必须在不使用库内置的 sort 函数的情况下解决这个问题。
Intro
Ref Link:https://leetcode.cn/problems/sort-colors/
Difficulty:Medium
Tag:Array、Math、Two Pointers
Updated Date:2023-06-13
Test Cases
示例1:
输入:nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]
示例 2:
输入:nums = [2,0,1]
输出:[0,1,2]
提示:
n == nums.length
1 <= n <= 300
nums[i] 为 0、1 或 2
进阶:
你能想出一个仅使用常数空间的一趟扫描算法吗?
思路1:
- 定义两个指针,zeroIndex初始值是 0,twoIndex初始值是 nums.length - 1
- 一次遍历数组
遇到0放前面,zeroIndex++
遇到2放后面,twoIndex–,此时未知值换到了前面,注意 i–,下次继续判断该元素 - 特别注意,for循环的条件,已经换好的twoIndex后,不再重复遍历 i <= twoIndex && zeroIndex < twoIndex
Code AC 1
class Solution {
public void sortColors(int[] nums) {
int zeroIndex = 0;
int twoIndex = nums.length - 1;
for (int i = 0; i <= twoIndex && zeroIndex < twoIndex; i++) {
if (nums[i] == 0) {
nums[i] = nums[zeroIndex];
nums[zeroIndex] = 0;
zeroIndex++;
}
if (nums[i] == 2) {
nums[i] = nums[twoIndex];
nums[twoIndex] = 2;
twoIndex--;
i--;
}
}
}
}
思路2:
- 定义两个指针,zeroIndex 和 oneIndex,表示下一个 0 和 1要放置的位置,初始值都是 0
- 一次遍历数组
- 遇到 0 放 zeroIndex 的位置,特别注意的是!!此时如果 0 后已有排序好的 1, 即 if (zeroP < oneP),把 0 交换到前面的操作会把 1 覆盖掉,此时需要把这个被覆盖掉的 1 移动新的 oneIndex 的位置。最后 zeroIndex++, oneIndex++ 移动指针。
- 遇到 1 放 oneIndex 的位置,oneIndex++
Code AC 2
class Solution {
public void sortColors3(int[] nums) {
if (nums == null) return;
int zeroP = 0;
int oneP = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
nums[i] = nums[zeroP];
nums[zeroP] = 0;
if (zeroP < oneP) {
nums[i] = nums[oneP];
nums[oneP] = 1;
}
oneP++;
zeroP++;
} else if (nums[i] == 1) {
nums[i] = nums[oneP];
nums[oneP] = 1;
oneP++;
}
}
}
}
Accepted
87/87 cases passed (0 ms)
Your runtime beats 100 % of java submissions
Your memory usage beats 66.27 % of java submissions (39.9 MB)
复杂度分析
- 时间复杂度:O(n)
- 空间复杂度:O(1)