【leetcode】排序算法总结

【leetcode】排序算法总结

算法名称 稳定性 时间复杂度 空间复杂度

堆排序

  • 面试题40. 最小的k个数
class Solution {
public:
    vector<int> getLeastNumbers(vector<int>& arr, int k) {
       //将前k个建立大堆
       maxheap(arr, 0, k-1);
       for(int i=k/2-1; i>=0; i--){
           maxheap(arr, i, k-1);
       }
       for(int i=k; i<arr.size(); ++i){
           if(arr[i]>arr[0]) continue;
           else{
               int temp = arr[i];
                arr[i] = arr[0];
                arr[0] = temp;

                maxheap(arr, 0, k-1);
           }
       }
       vector<int> res(arr.begin(), arr.begin()+k);
       return res;
    }

    void maxheap(vector<int>& arr, int start, int end){
        int dad = start;
        int son = dad * 2 + 1;
        while(son <= end){
            if(son + 1 <= end && arr[son] < arr[son + 1]){
                son ++;
            }
            if(arr[dad] >= arr[son]){
                return;
            }
            else{
                int temp = arr[dad];
                arr[dad] = arr[son];
                arr[son] = temp;

                dad = son;
                son = dad * 2 + 1;
            }
        }
    }
};
发布了86 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36530992/article/details/105009369
今日推荐