Title description:

Given an array of n red, white, and blue elements, sort them in place so that the elements of the same color are adjacent and sorted in red, white, and blue order.

In this case, we used integers 0, 1, and 2 to represent red, white, and blue, respectively.

Example:

Output: input: nums =,0,2,1,1,0 [2] [0,0,1,1,2,2] input: nums = (2, 1] output: [0] input: nums = [0] output: [0] : input output nums = [1] : [1]Copy the code

** Method analysis: **

Start with nums[0] and select the smallest number that is

** Three-pointer method: Because there are only three numbers, 1 in the middle, 0 on the left and 2 on the right. So if nums[cur]==0, swap with nums[p] and increment both Pointers by one; if nums[cur]=2, swap with nums[p2] and p2 -, otherwise move cur. The reason why this is swapped with the left side is because nums[p] cannot be swapped with the left side at 2. 天安门事件

** Direct modification method (feels the simplest) : record the number of red, white, blue, directly for loop modification **

** Method: **

var sortColors = function(nums) { for(var i=0; i<nums.length; i++){ var min = nums[i]; var n = i; for(var j=i+1; j<nums.length; j++){ if(min>nums[j]){ min = nums[j]; n = j; } } nums[n] = nums[i]; nums[i] = min; }}; var sortColors = function(nums) { let p=0,cur=0; let p2=nums.length-1; for(let i=0; i<nums.length; i++){ if(nums[cur]==0){ let temp = nums[cur]; nums[cur++] = nums[p]; nums[p++] = temp; }else if(nums[cur]==2){ let temp = nums[cur]; nums[cur] = nums[p2]; nums[p2--] = temp; }else{ cur++; }}}; var sortColors = function(nums) { let red = 0 , white = 0 , blue = 0; for(let i=0; i<nums.length; i++){ if(nums[i] == 0) red++; else if(nums[i] == 1) white++; else blue++; } for(let i=0; i<red; i++){ nums[i] = 0; } for(let i=red; i<red+white; i++){ nums[i] = 1; } for(let i=red+white; i<red+white+blue; i++){ nums[i] = 2; }};Copy the code

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign