Title Description
Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He colors in the order red, white and blue.
Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You is not a suppose to use the library's sort function for this problem.
In fact, is the tricolour problem, give 3 numbers 0,1,2, sort them well.
Solution One:
Three traversal.
Ideas:
First look at 2 from the left, 0 on the right, the first traversal, to ensure that 0 on the left of 2;
From the left to find 1, the right to find 0, the second traversal, to ensure that 0 on the left of 1;
Look for 2 from the left, 1 on the right, third traversal, 1 on the left of 2.
Implementation code:
public class Solution {public void Sortcolors (int[] nums) { findandswap (nums, 0, 2); Findandswap (nums, 0, 1); Findandswap (Nums, 1, 2); } public void Findandswap (int[] nums, int left, int. right) {var i = 0;var k = nums. Length-1;while (I < k) {while (nums[i]! = Right && i < k) { i++; } while (nums[k]! = Left && k > 0) { k--; } if (I < k) {var t = nums[i];nums[i] = nums[k];nums[k] = t;}}}
Solution Two:
In fact, the subject by the region to understand, only need to traverse once.
Ideas:
I,j,k indicates the area subscript of 0,1,2 respectively.
1. If j is 1, go down: j + +; If j is 0, swap nums[i] and nums[j] and i++,j++. The first step is to ensure that the 0 zone is on the left of the 1 area
2. If J is 2, start looking from the right (k=length-1,k--), find not 2, swap nums[j] and nums[k] and k--, this step is to ensure that 2 is on the right side of the 0 and 1 zones.
Implementation code:
public class Solution {public void Sortcolors (int[] nums) { var i = 0; var k = nums. Length-1; var j = 0; while (J <= k) { if (nums[j] = = 1) { j + +; } else if (nums[j] = = 0) { var t = nums[i]; Nums[i] = nums[j]; NUMS[J] = t; j + +; i++; } else{ while (nums[k] = = 2 && J < k) { k--; } var t = nums[j]; NUMS[J] = nums[k]; Nums[k] = t; k--;}}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Sort Colors