1. The Dutch tricolor flag problem
Problem description: An array contains only three elements: 0, 1, and 2. Without counting sorting, place 0 to the left of 1 and 2 to the right of 1.
analyze:
1. The idea of division in quicksort can be used for reference. Divide the array into {0 area}, arr[], {2 area}
2. Traverse arr, when 0 is found, area 0 expands to the right, when 2 is found, area 2 expands to the left,
3. When the current element enters zone 2, it ends.
vector<int> sortThreeColor(vector<int> A, int n) { // write code here int last0=-1; int first2=n; for(int i=0;i<n;i++){ if(i==first2) break; if(A[i]==0){ int temp=A[last0+1]; A[last0+1]=0; last0 ++ ; A[i]=temp; } if(A[i]==2){ int temp=A[first2-1]; A[first2-1]=2; first2--; A[i]=temp; i -- ;//(Because the number exchanged in area 2 has not been judged, it needs to be judged again) } } return A; }
2. The problem of finding elements in a row-column matrix
Problem description: Find an element in a two-dimensional matrix with ordered rows and columns.
Such as matrix: 1 2 3 4 find element 6
2 3 3 4
3 4 6 7
Analysis: First start from the upper right corner of the matrix, if the current element e>6, go left, that is, column -1, if e<6, go down, that is, row +1, otherwise find.
If the current element subscript is outside the bounds of the matrix, it cannot be found.