LeetCode Top 100 Liked Questions 75. Sort Colors (Java版; Medium)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Top 100 Liked Questions 75. Sort Colors (Java版; Medium)相关的知识,希望对你有一定的参考价值。
welcome to my blog
LeetCode Top 100 Liked Questions 75. Sort Colors (Java版; Medium)
题目描述
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 librarys sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
class Solution
public void sortColors(int[] nums)
int n = nums.length;
if(n<=1)
return;
partition(nums, 0, n-1);
private void partition(int[] nums, int L, int R)
int small=L-1, big=R+1;
int p = L;
while(p<big)
if(nums[p] < 1)
swap(nums, ++small, p++);
else if(nums[p] > 1)
swap(nums, --big, p);
else
p++;
private void swap(int[] arr, int i, int j)
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
荷兰国旗, 实际上就是执行了一次partition; 关键点: 循环终止条件
第二次做; 最朴素的想法: 桶排序; 时间复杂度O(N^2), 不推荐这个方法
class Solution
public void sortColors(int[] nums)
//用计数排序解决一次
int[] arr = new int[3];
for(int a : nums)
arr[a]++;
//从桶中倒出来
int j = 0;
for(int i=0; i<arr.length; i++)
while(arr[i]>0)
nums[j++] = i;
arr[i]--;
第一次做, 荷兰国旗问题, 遍历一次数组即可; partition将数组分成三部分:小于区,等于区,大于区; 口诀:换扩跳, 换扩, 跳; 细节: 必须用1作为划分值, 因为题目要求1在等于区; 小于区向右扩, 大于区向左扩, 剩下的是等于区;
/*
荷兰国旗问题,就是一轮partition过程
将数组分成三个部分
细节:划分值必须选1, 因为题目规定了1在中间, 所以不能选0或者2在中间
*/
class Solution
public void sortColors(int[] nums)
if(nums==null || nums.length==0)
return;
int small = -1;//小于区向右扩
int big = nums.length; //大于区向左扩
int pivot = 1; //划分值必须选1, 因为题目规定了1在中间
int i = 0;
while(i<big)
if(nums[i] < pivot)
swap(nums, i++, ++small);
else if(nums[i] > pivot)
swap(nums, i, --big);
else
i++;
public static void swap(int[] arr, int i, int j)
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
以上是关于LeetCode Top 100 Liked Questions 75. Sort Colors (Java版; Medium)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Top 100 Liked Questions 85. Maximal Rectangle (Java版; Hard)
LeetCode Top 100 Liked Questions 10.Regular Expression Matching (Java版; Hard)
LeetCode Top 100 Liked Questions 142. Linked List Cycle II (Java版; Medium)
LeetCode Top 100 Liked Questions 98. Validate Binary Search Tree (Java版; Medium)
LeetCode Top 100 Liked Questions 124. Binary Tree Maximum Path Sum (Java版; Hard)