给定一个包含红色、白色和蓝色、共 n
个元素的数组 nums
,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 0
、 1
和 2
分别表示红色、白色和蓝色。
必须在不使用库内置的 sort 函数的情况下解决这个问题。
示例 1:
输入:nums = [2,0,2,1,1,0] 输出:[0,0,1,1,2,2]
示例 2:
输入:nums = [2,0,1] 输出:[0,1,2]
我的思路:
使用一个可以内部实现排序的TreeMap
map.getOrDefault(x, 0)
:- 这个方法尝试从
map
中获取与键x
相关联的值。 - 如果
map
中已经存在键x
,则返回与x
相关联的值。 - 如果
map
中不存在键x
,则返回方法调用时提供的默认值,这里是0
- 这个方法尝试从
-
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
for (Map.Entry<Integer, Integer> entry : map.entrySet()) { ... }
这行代码是Java中的一个增强型for
循环(也称为"for-each"循环),用于遍历Map
接口中的entrySet()
方法返回的集合。这个集合包含了Map
中所有的键值对(Map.Entry
对象),每个Map.Entry
都代表了一个键和一个与之关联的值。
class Solution {
public void sortColors(int[] nums) {
Map<Integer,Integer>map=new TreeMap<>();
for(int x:nums){
map.put(x,map.getOrDefault(x,0)+1);
}
int index = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int key = entry.getKey(); // 颜色值(0, 1, 2)
int count = entry.getValue(); // 该颜色的数量
// 将该颜色的元素填充到nums数组中
while (count > 0) {
nums[index++] = key;
count--;
}
}
}
}
看了力扣官方的解答之后发现这是一个经典的荷兰国旗问题:
这是我在官方视频里面截的图:
其实我个人感觉这个思路不是很好理解,代码大家自己看吧
class Solution {
public void sortColors(int[] nums) {
int n = nums.length;
int p0 = 0, p1 = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] == 1) {
int temp = nums[i];
nums[i] = nums[p1];
nums[p1] = temp;
++p1;
} else if (nums[i] == 0) {
int temp = nums[i];
nums[i] = nums[p0];
nums[p0] = temp;
if (p0 < p1) {
temp = nums[i];
nums[i] = nums[p1];
nums[p1] = temp;
}
++p0;
++p1;
}
}
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/sort-colors/solutions/437968/yan-se-fen-lei-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。