Kth Largest Element in an Array

    xiaoxiao2021-03-25  69

    

    Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

    For example, Given [3,2,1,5,6,4] and k = 2, return 5.

    Note: You may assume k is always valid, 1 ≤ k ≤ array's length.

    Solution:

    class Solution { public:     int findKthLargest(vector<int>& nums, int k) {         vector<int> n = nums;         int temp;         for (int i = 1; i < n.size(); i++)             for (int j = n.size() - 1; j >= i; j--)                 if (n[j] > n [j - 1]) {                     temp = n[j];                     n[j] = n[j - 1];                     n[j - 1] = temp;                 }         return n[k - 1];     } };

    转载请注明原文地址: https://ju.6miu.com/read-40564.html

    最新回复(0)