215. 数组中的第K个最大元素

215. 数组中的第K个最大元素

链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/

题解:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode/

class Solution {
    public:
        int partition(vector<int>* arr, int low, int high) {                                                   
            int small = low-1;                                                                                 
            for (; low < high; ++low) {                                                                        
                if ((*arr)[low] < (*arr)[high]) {                                                              
                    ++small;                                                                                   
                    if (small != low) {                                                                        
                        swap((*arr)[small], (*arr)[low]);                                                      
                    }                                                                                          
                }                                                                                              
            }                                                                                                  
            ++small;                                                                                           
            if (small != high) {                                                                               
                swap((*arr)[small], (*arr)[low]);                                                              
            }                                                                                                  
            return small;                                                                                      
        }
        int findKthLargest(vector<int>& nums, int k) {
            if(nums.size() == 0) return -1;
            // 先排序一次
            int index = partition(&nums, 0, nums.size()-1);
            int low = 0;
            int high = nums.size()-1;
            // 求第k个大的数字的下表
            int need_index = nums.size()-k;
            // 如果index 等于 need_index,则nums[need_index]为第k个大的数字
            while (index != need_index) {
                // 调整low和high的下表
                if (index > need_index) {
                    high = index-1;
                } else {
                    low = index+1;
                }
                index = partition(&nums, low, high);
            }
            return nums[need_index];
        }
};

 

上一篇:[周末训练]数字计数


下一篇:ISO Latin-1字符集