A 9ms C++ solution in 4 lines


  • 1
    P

    I recently came across a C++ function called nth_element( ). Thanks to @StefanPochmann . What this function does is partially sort the vector in such a way that the element in the position you specify is changed to element it will have if it was a sorted array.

    The code is as follows:

    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            int size = nums.size();
            if (size == 0 || k >size) return -1;
            nth_element(nums.begin(), nums.end() -k, nums.end()); // since the element i want is in nums.end() -k position
            return nums[size-k];
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.