25, 75. 颜色分类
https://leetcode-cn.com/problems/sort-colors/
思路1:调用内置方法
思路2:
-
左起一个指针,
-
然后先遍历一遍数组到时候,发现0和指针交换,指针后移
-
再遍历一遍数组,发现1和指针交换,指针后移
-
然后done
思路3:计数排序
思路4:双指针
- https://leetcode-cn.com/problems/sort-colors/solution/yan-se-fen-lei-by-leetcode-solution/
package com.shangguigu.dachang.algrithm.A08_sort;
import java.util.Arrays;
import java.util.HashMap;
/**
* @author : 不二
* @date : 2022/4/20-上午9:42
* @desc : 75. 颜色分类
* https://leetcode-cn.com/problems/sort-colors/
**/
public class A84_sortColors {
public static void main(String[] args) {
// int[] nums = {2, 0, 2, 1, 1, 0};
// int[] nums = {2, 0, 2, 1, 1, 0};
// int[] nums = {2, 0, 1};
int[] nums = {1, 0, 1};
// sortColors_v1(nums);
// sortColors_v2(nums);
// sortColors_v3(nums);
// sortColors_v3(nums);
sortColors_v4(nums);
System.out.println(Arrays.toString(nums));
}
/**
* 思路4:双指针
* https://leetcode-cn.com/problems/sort-colors/solution/yan-se-fen-lei-by-leetcode-solution/
* 知道大概意思,没理解透测。
*/
public static void sortColors_v4(int[] nums){
int n = nums.length;
int p0 = 0, p1 = 0;
for (int i = 0; i < n; ++i) {
// p1用来交换1
if (nums[i] == 1) {
int temp = nums[i];
nums[i] = nums[p1];
nums[p1] = temp;
++p1;
} else if (nums[i] == 0) {
// p0用来把0往前放, p0往前放后,那么还需要判断交换后的数据是否需要再交换
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;
}
}
}
/**
* 思路3:计数排序
*/
public static void sortColors_v3(int[] nums){
int[] state = new int[3];
// 统计出每个数字有几个
for (int i = 0; i < nums.length; i++) {
state[nums[i]] = state[nums[i]] + 1;
}
int index = 0;
// 然后从小到大,根据数字的个数,直接补充到数组中
for (int i = 0; i < state.length; i++) {
int count = state[i];
while (count > 0) {
nums[index++] = i;
count--;
}
}
}
/**
* 思路2:左起一个指针,
* 然后先遍历一遍数组到时候,发现0和指针交换,指针后移
* 再遍历一遍数组,发现1和指针交换,指针后移
* 然后done
*/
public static void sortColors_v2(int[] nums){
int pointer = 0;
int temp;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
temp = nums[i];
nums[i] = nums[pointer];
nums[pointer] = temp;
pointer++;
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
temp = nums[i];
nums[i] = nums[pointer];
nums[pointer] = temp;
pointer++;
}
}
}
/**
* 思路1:调用内置方法
*/
public static void sortColors_v1(int[] nums) {
Arrays.sort(nums);
}
}