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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

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

Rust Solution

struct Solution;
use std::cmp::Ordering::*;

trait Partition {
    fn partition(&mut self, l: usize, r: usize) -> usize;
}

impl Partition for Vec<i32> {
    fn partition(&mut self, l: usize, r: usize) -> usize {
        self.swap((l + r) / 2, r);
        let mut j = l;
        let pivot = self[r];
        for i in l..r {
            if self[i] <= pivot {
                self.swap(i, j);
                j += 1;
            }
        }
        self.swap(j, r);
        j
    }
}

impl Solution {
    fn find_kth_largest(mut nums: Vec<i32>, k: i32) -> i32 {
        let n = nums.len();
        let mut l = 0;
        let mut r = n - 1;
        let k = n - k as usize;
        while l < r {
            let m = nums.partition(l, r);
            match m.cmp(&k) {
                Less => {
                    l = m + 1;
                }
                Greater => {
                    r = m - 1;
                }
                Equal => {
                    break;
                }
            }
        }
        nums[k]
    }
}

#[test]
fn test() {
    let nums = vec![3, 2, 1, 5, 6, 4];
    let k = 2;
    let res = 5;
    assert_eq!(Solution::find_kth_largest(nums, k), res);
}

Having problems with this solution? Click here to submit an issue on github.