Algorithm idea:
The problem is a sorting problem, which can be divided into the front, middle, and rear parts of the array. Here's the idea: put the front and rear rows in front and back of the array, and the middle is naturally lined up. Set three pointers:begin,mid,end, and then traverse from the position of mid.
1. If the traversed position is 0, then it belongs to the front, swap mid and begin , then mid and begin to move forward.
2. If the traversed position is 1, it is in the middle, then only mid is moved.
3. If the traversed position is 2, then it belongs to the rear, and the mid and end are exchanged, since the swap mid The pointer is indeterminate, so only the end-- .
voidSortcolors (vector<int>&nums) { intbegin=0, End=nums.size ()-1, mid=0; while(mid<=end&&begin<=mid) { if(nums[mid]==0) {swap (nums[mid],nums[begin]); Begin++; Mid++; } Else if(nums[mid]==1) Mid++; Else if(nums[mid]==2) {swap (nums[mid],nums[end]); End--; } }}
Sort color (flag of the Netherlands)