Software Enginner πŸ‡―πŸ‡΅ and πŸ‡°πŸ‡·

Leetcode - 215.Kth Largest Element in an Array

Problem Kth Largest Element in an Array
Difficulty Medium
Language Java
Time complexity $$O(2n)$$
Space complexity $$O(2n)$$

Problem,

Given an integer array nums and an integer k, return the kth largest element in the array.

Note that it is the kth largest element in the sorted order, not the kth distinct element.

Can you solve it without sorting?

Example 1:

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

Example 2:

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

Solution,

정렬을 μ‚¬μš©ν•˜μ§€ λͺ»ν•œλ‹€. μš°μ„  λ‚˜λŠ” \(-10^4 <= N <= 10^4\) κ°€ 보μž₯λ˜μ—ˆλ‹€ ν•˜μ˜€μœΌλ‹ˆ, κ³΅κ°„λ³΅μž‘λ„λ₯Ό ν¬κΈ°ν•˜κ³  ν’€μ—ˆλ‹€.

class Solution {
    private static final int MAGIC = 10000;
    public int findKthLargest(int[] nums, int k) {
        int[] order = new int[20001];
        for (int num : nums) {
            order[num < 0 ? (num + MAGIC) : num + MAGIC] += 1;
        }

        for (int i = order.length - 1, m = k, s = 0; i >= 0; --i) {
            if (order[i] > 0) 
                m -= order[i];
            if (m <= 0) 
                return i < MAGIC ? i - MAGIC : i - MAGIC;
        }

        return 0;
    }
}