Main topic:
Give you a red, white, blue array of three colors, ordered according to the Order of red, white, and blue, Leetcode link: https://leetcode.com/problems/sort-colors/
Idea 1:
Sort the entire array directly, time complexity O (NLOGN)
Idea 2:
Count sorting method, use a hash-like array to record the number of each color, and then sort, but need to traverse the original array two times
Idea 3:
Using three pointers, P1 represents the dividing line between red and white, p2 represents the dividing line between white and blue, and I represents the current element
That is, 0~p1-1 is red, p1~i-1 is white, p2+1~n-1 means blue.
1) If the current element is red, it is exchanged with the element pointed to by P1, because the color I refer to after the interchange is white, I traverse the next element directly
2) If the current element is blue, it is exchanged with the element pointed to by the P2, because the color I refer to after the interchange may be white, it may be red, so I need to rewind I
The implementation code is as follows: note I should be between [P1,P2]
classsolution{ Public: voidSortcolors (vector<int>&nums) { intn =nums.size (); if(N <=1) { return; } intP1 =0; intP2 = n-1; //Notice the cyclic condition of I for(intI=0; i<=p2; ++i) {if(Nums[i] = =0) {swap (NUMS[P1], nums[i]); ++P1; } Else if(Nums[i] = =2) {swap (NUMS[P2], nums[i]); --P2; --i; } } }Private: voidSwapint&a,int&b) {intTMP =A; A=b; b=tmp; }};
Three-color sorting