linkcode143. 排颜色

时间:2020-04-13
本文章向大家介绍linkcode143. 排颜色,主要包括linkcode143. 排颜色使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

链接:https://www.lintcode.com/problem/sort-colors-ii/description

快排:(不用sort进行排序)

 1 class Solution {
 2 public:
 3     /**
 4      * @param colors: A list of integer
 5      * @param k: An integer
 6      * @return: nothing
 7      */
 8     void sortColors2(vector<int> &colors, int k) {
 9         // write your code here
10         //pivot
11         sort(colors,0,colors.size()-1,1,k);
12     }
13     void sort(vector<int>& colors,int left,int right,int colorfrom,int colorto){
14         if(colorfrom==colorto ||left>=right){
15             return;
16         }
17         int colormid=(colorfrom+colorto)/2;
18         int l=left,r=right;
19         while(l<=r){
20             while(l<=r&&colors[l]<=colormid){
21                 l++;
22             }
23             while(r>=l&&colors[r]>colormid){
24                 r--;
25             }
26             //swap
27             if(l<=r)
28             {
29                 int temp=colors[l];
30                 colors[l]=colors[r];
31                 colors[r]=temp;
32                 l++;
33                 r--;
34             }
35         }
36         sort(colors,left,r,colorfrom,colormid);
37         sort(colors,l,right,colormid+1,colorto);
38     }
39 };

原文地址:https://www.cnblogs.com/sweetlittlebaby/p/12691987.html