将乱序的红白蓝三色小球排列成有序的红白蓝三色的同颜色在一起的小球组。
这个问题之所以叫荷兰国旗,是因为我们可以将红白蓝三色小球想象成条状物,有序排列后正好组成荷兰国旗。
等价于:
给定一个数组arr, 和一个数num
请把小于num的数放在数组的左边
等于num的数放在数组的中间
大于num的数放在数组的右边
额外空间复杂度O(1), 时间复杂度O(N)
这个与快排中的partition部分非常近似。
在left和right范围内,划分区域,
初始区域为 low 指向<num的位置,high指向>num的位置,
然后left遍历数组,当
遇到<num的值时,将left处的值与low+1处的值交换,low++,且left++,
遇到=num的值时,left++,
遇到>num的值时,将left处的值与high-1处的值交换,high++,但是left不加1
终止条件:left与high相等
返回等于num的范围区间
public class Partition {
public void partition(int[] arrays, int num){
if(arrays == null || arrays.length == 0) return;
int[] res = partition(arrays, num, 0, arrays.length - 1);
for(int i = 0; i < arrays.length; i++){
System.out.print(arrays[i] + " ");
}
System.out.println();
System.out.println(res[0]);
System.out.println(res[1]);
}
public int[] partition(int[] arrays, int num, int left, int right){
int low = left - 1;
int high = right + 1;
while(left < high){
if(arrays[left] == num){
left++;
} else if(arrays[left] < num){
swap(arrays, ++low, left++);
} else{
swap(arrays, --high, left);
}
}
return new int[]{low + 1, high - 1};
}
public void swap(int[] arrays, int left, int right){
int temp = arrays[left];
arrays[left] = arrays[right];
arrays[right] = temp;
}
public static void main(String[] args){
int [] arrays = {4, 7, 9, 1, 8, 3, 4, 5, 3, 2, 6, 3};
Partition partition = new Partition();
partition.partition( arrays, 4 );
}
}