美文网首页
WEEK#11 Divide and Conquer_Kth L

WEEK#11 Divide and Conquer_Kth L

作者: DarkKnightRedoc | 来源:发表于2017-09-22 13:35 被阅读0次

    The code is pretty self-explained enough...
    When it comes to the Kth smallest:


    algorithm2.png
    algorithm.png

    Note that the choosing of the pivot value is up to the programmer

    class Solution {
    public:
        bool flag = false;
    
        int findKthLargest(vector<int>& nums, int k) {
            if (flag == false) {
                k -= 1;
                flag = true;
            }
            int pivot, pivotindex;
            vector<int> larger, equal, smaller;
            pivotindex = nums.size()/2; // generate a random number between 0 ~ num.size()
            pivot = nums[pivotindex];
            for (auto i : nums) {
                if (i < pivot) {
                    smaller.push_back(i);
                }
                else if (i == pivot) {
                    equal.push_back(i);
                }
                else if (i > pivot) {
                    larger.push_back(i);
                }
            }
            if (k < larger.size())
                return findKthLargest(larger, k);
            else if (k >= larger.size() && k < larger.size() + equal.size()) {
                return pivot;
                flag = false;
            }
            else if (k >= larger.size() + equal.size())
                return findKthLargest(smaller, k-larger.size()-equal.size());
        }
    };
    

    相关文章

      网友评论

          本文标题:WEEK#11 Divide and Conquer_Kth L

          本文链接:https://www.haomeiwen.com/subject/bhhfextx.html