1. 程式人生 > >LN : leetcode 215 Kth Largest Element in an Array

LN : leetcode 215 Kth Largest Element in an Array

kth .com distinct cnblogs des leetcode 轉化 solution n-k

lc 215 Kth Largest Element in an Array


215 Kth Largest Element in an Array

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.

multiset Accepted

投機取巧的方法,利用stl中multiset的特性,自動實現從小到大的排序,並且允許有相同元素的存在,但是要註意,multiset不能用下標獲取元素,所以需刪除之前不必要的元素,用*ans.begin()的方法獲取首元素。

class Solution {
public:
int findKthLargest(vector

分治 Accepted

類似於快排的原理,其中也蘊含了分治的思想。

class Solution {
public:
    void swap(vector<int>& nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    int findKthLargest(vector<int>& nums, int k) {
        int n = nums.size();
        int p = quick(nums, 0, n-1, n-k+1);
        return nums[p];
    }
    
    int quick(vector<int>& a, int low, int high, int k) {
        int i = low, j = high, pivot = a[high];
        while (i < j) {
            if (a[i++] > pivot) swap(a, --i, --j);
        }
        swap(a, i, high);
        int m = i - low + 1;
        if (m == k)     return i;
        else if (m > k) return quick(a, low, i - 1, k);
        else            return quick(a, i + 1, high, k - m);
    }
};

將遞歸轉化成遞推

思想和上面的方法是一樣的,但是將遞歸轉化成遞推。

class Solution {
public:
void swap(vector

int findKthLargest(vector<int>& nums, int k) {
    k = nums.size() - k;
    int l = 0, r = nums.size() - 1;
    while (l <= r) {
        int i = l;
        for (int j = l + 1; j <= r; j++)
            if (nums[j] < nums[l]) swap(nums, j, ++i);
        swap(nums, l, i);

        if (k < i) r = i - 1;
        else if (k > i) l = i + 1;
        else return nums[i];
    }
    return -1;
}

};

LN : leetcode 215 Kth Largest Element in an Array