第k大元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_36346463/article/details/80998331

在数组中找到第k大的元素

你可以交换数组中的元素的位置

Have you met this question in a real interview?   Yes

Example

给出数组 [9,3,2,4,8],第三大的元素是 4

给出数组 [1,2,3,4,5],第一大的元素是 5,第二大的元素是 4,第三大的元素是 3,以此类推

Challenge

要求时间复杂度为O(n),空间复杂度为O(1)

class Solution {
public:
    /*
     * @param n: An integer
     * @param nums: An array
     * @return: the Kth largest element
     */
    int kthLargestElement(int n, vector<int> &nums) {
        // write your code here
        if (nums.size() == 0 || n == 0 || n > nums.size()) {
            return 0;
        }
        return getKthLargestElement(nums, 0, nums.size() - 1, n);
    }
    int getKthLargestElement(vector<int> &nums, int start, int end, int n) {
        if (start == end) {
            return nums[n - 1];
        } else {
            int i = start;
            int j = end;
            while (i < j) {
                while(i < j && nums[i] > nums[j]) {
                    i++;
                }
                if (i < j) {
                    swap(nums[i],nums[j]);
                    j--;
                }
                while(i < j && nums[i] > nums[j]) {
                    j--;
                }
                if (i < j) {
                    swap(nums[i],nums[j]);
                    i++;
                }
            }
            if (i + 1 == n) {
                return nums[i];
            } else if (i + 1 > n) {
                return getKthLargestElement(nums, start, i - 1, n);
            } else {
                return getKthLargestElement(nums, i + 1, end, n);
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36346463/article/details/80998331