topK算法

一个不错的topK的示例代码!

class Solution {
public:
    void adjust(vector &arr, int index, int len) {
        int left = 2 * index + 1;
        int right = 2 * index + 2;
        int max_index = index;
        if (left < len && arr[left] > arr[max_index]) max_index = left;
        if (right < len && arr[right] > arr[max_index]) max_index = right;
        if (max_index != index) {
            swap(arr[max_index], arr[index]);
            adjust(arr, max_index, len);
        }
    } 

    void heapSort(vector &arr, int len) {
        for (int i = len / 2 - 1; i >= 0; i--) {
            adjust(arr, i, len);
        }
        // for (int i = len - 1; i >= 1; i--) {
        //     swap(arr[0], arr[i]);
        //     adjust(arr, 0, i);
        // }
    }

    vector GetLeastNumbers_Solution(vector input, int k) {
        if (k <= 0 || k > input.size()) {
            vector nullVec;
            return nullVec;
        }
        // 因为要取最小的k个数,所以取前k个数字构建一个最大堆
        // 相反,如果是取最大的k个数,则构建一个最小堆
        vector sortedArray(input.begin(), input.begin() + k);
        heapSort(sortedArray, k);
        // 将后面的数字与这个构建好的二叉堆进行比较 
        for (int i = k; i < input.size(); i++) {
            if (input[i] < sortedArray[0]) {
                sortedArray[0] = input[i];
                adjust(sortedArray, 0, k);
            }
        }
        for (int i = k - 1; i >= 1; i--) {
            swap(sortedArray[0], sortedArray[i]);
            adjust(sortedArray, 0, i);
        }
        return sortedArray;
    }
};

int main( )
{
    int A[10] ={9,10,5,7,8,9,2,4,6,3};
    //quick_sort(A, 0, 9);
    Solution S;
    vector B ={9,10,5,7,8,9,2,4,6,3};
    // S.heapSort(B, 10);
    vector C = S.GetLeastNumbers_Solution(B, 4);
    for (int i = 0; i<4; ++i)
    	std::cout<

 

你可能感兴趣的:(算法)