leetcode #215. Kth Largest Element in an Array 分治

 

class Solution {
    set xx;
private:
    int findKthLargest(const vector& nums, int k, int target) {
        vector minVec;
        vector maxVec;
        int eqCnt = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] < target) {
                minVec.push_back(nums[i]);
            }
            if (nums[i] > target) {
                maxVec.push_back(nums[i]);
            }
            if (nums[i] == target) {
                eqCnt ++;
            }
        }
        if (maxVec.size() < k && maxVec.size() + eqCnt >= k) {
            return target;
        } else {
            xx.insert(target);
            if (maxVec.size() >= k) {
                for (int j = 0 ; j < maxVec.size(); j++) {
                    if (!xx.count(maxVec[j])) {
                        target = maxVec[j];
                    }
                }
            } else {
                for (int j = 0 ; j < minVec.size(); j++) {
                    if (!xx.count(minVec[j])) {
                        target = minVec[j];
                    }
                }
            }
            return findKthLargest(nums, k, target);
        }
    }
public:
    int findKthLargest(vector& nums, int k) {
        if (nums.size() < k) {
            return -1;
        }
        int tempTarget = nums[0];
        return findKthLargest(nums, k, tempTarget);
    }
};

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