Kth Largest Element in an Array

Pretty simple Question!

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

์•Œ๊ณ ๋ฆฌ์ฆ˜ #1 K๋ฒˆ์งธ ํฐ ์›์†Œ๋Š” ์ •๋ ฌ๋œ ์ƒํƒœ์˜ ๋ฐฐ์—ด์—์„œ [๋ฐฐ์—ด์˜ ๊ธธ์ด-K] ๋ฐฉ์— ์žˆ๋Š” ์›์†Œ๋‹ค! 1. ๋ฐฐ์—ด ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ - Arrays.sort() ์ด์šฉ 2. K๋ฒˆ์งธ ํฐ ์›์†Œ ๋ฆฌํ„ด - nums[nums.length-K]

์•Œ๊ณ ๋ฆฌ์ฆ˜ #2 ์šฐ์„ ์„ ์œ„ ํ(์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ, ์ตœ์†Œํž™)๋ฅผ ์ด์šฉํ•˜์—ฌ ํ‘ผ๋‹ค. 1. ์˜ค๋ฆ„์ฐจ์ˆœ์˜ ์ตœ์†Œํž™ ํ๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ๋ฐฐ์—ด์˜ ๋ฐ์ดํ„ฐ๋ฅผ ํ์— ๋„ฃ๋Š”๋‹ค. - .offer() 2. Kํฌ๊ธฐ ๋งŒํผ์˜ ํ๋ฅผ ์œ ์ง€ํ•œ๋‹ค. - .poll() 3. ๋งˆ์ง€๋ง‰์— ํ์˜ ํ—ค๋“œ๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค. - .peek()

class Solution {
    public int findKthLargest(int[] nums, int k) {
        
        //1. Array๋กœ ํ’€๊ธฐ
        int length = nums.length;
        Arrays.sort(nums);
        return nums[length-k];
        //2. PriorityQueue๋กœ ํ’€๊ธฐ
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>(Comp);
        for(int i:nums) {
            pq.offer(i);
            if(pq.size() > k) {
                pq.poll();
            }
        }
        return pq.peek();
    }
    
    Comparator<Integer> Comp = new Comparator<Integer>() {
        public int compare(Integer a, Integer b) {
            return a-b;
        }
    };
}

Last updated