row Color II
Given an array of n objects (including k different colors, numbered 1 to K), the objects are categorized so that objects of the same color are adjacent and sorted in the order of 1,2,...K.
Sample Example
Given the colors= [3, 2, 2, 1, 4] , k=4 your code should operate in place so that the array becomes[1, 2, 2, 3, 4]
Solving
Direct Quick-line
classSolution {/** * @paramcolors:a List of integers *@paramK:an Integer *@return: Nothing*/ Public voidSortColors2 (int[] Colors,intk) {//Write your code hereSort (colors,0,colors.length-1); } Public voidSortint[] A,intLowintHigh ) { if(Low >=High )return ; inti =Low ; intj =High ; intTMP =A[low]; while(i<j) { while(I<j && a[j]>tmp) j--; if(i<j) {A[i]=A[j]; I++; } while(i<j && a[i]<= tmp) i++; if(i<j) {A[j]=A[i]; J--; }} A[i]=tmp; Sort (A,low,i-1); Sort (A,i+1, high); }}Java Code
notation, count the number of individual colors, and then change the number of changes in the array
classSolution {/** * @paramcolors:a List of integers *@paramK:an Integer *@return: Nothing*/ Public voidSortColors2 (int[] Colors,intk) {//Write your code here int[] flag =New int[K+1]; for(inti = 0;i<colors.length;i++) {Flag[colors[i]]++; } intc = 1; for(inti = 0;i<colors.length;i++){ while(flag[c]==0) {//the color may be 0 moreC++; } Colors[i]=C; FLAG[C]--; } } }View Code
Only three colors are sorted, but when there are multiple, it is too much to judge.
The method of seeing two pointers in nine chapters
classSolution {/** * @paramcolors:a List of integers *@paramK:an Integer *@return: Nothing*/ Public voidSortColors2 (int[] Colors,intk) {intCount = 0; intStart = 0; intEnd = Colors.length-1; while(Count <k) {intMin =Integer.max_value; intMax =Integer.min_value; for(inti = start; I <= end; i++) {min=math.min (min, colors[i]); Max=Math.max (Max, colors[i]); } intleft =start; intright =end; intCur =Left ; while(cur <=Right ) { if(Colors[cur] = =min) {Swap (left, cur, colors); Cur++; Left++; } Else if(Colors[cur] > Min && colors[cur] <max) {cur++; } Else { intTMP =Colors[cur]; Swap (cur, right, colors); Right--; }} Count+ = 2; Start=Left ; End=Right ; } } voidSwapintLeftintRightint[] colors) { intTMP =Colors[left]; Colors[left]=Colors[right]; Colors[right]=tmp; } }
The mind is too stupid to understand.
Lintcode: Row Color II