Kth Largest Element in an Array


🔗 質問リンク


https://leetcode.com/problems/kth-largest-element-in-an-array/

問題の説明


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.

⚠▼制限


  • 1<=k<=nums.length<=1041 <= k <= nums.length <= 10^41<=k<=nums.length<=104

  • −104<=nums[i]<=104-10^4 <= nums[i] <= 10^4−104<=nums[i]<=104
  • 💡 プール(言語:Java)


    これは単純に並べ替えてk位置のインデックスを返すだけで解決できる問題ですが、PriorityQueue(PriorityQueue)を使用して解決することもできます.
    import java.util.*;
    
    class Solution {
        public int findKthLargest(int[] nums, int k) {
            Queue<Integer> queue = new PriorityQueue<>();
            // 큐에 수를 넣어주면 알아서 오름차순으로 정렬됨
            for (int n : nums) {
                queue.offer(n);
                // K번쨰로 큰수는 정렬된 수중에 끝 K개의 수중에 제일 앞의 수
                // K개만 남기고 나머지는 버린다
                if (queue.size() > k)
                    queue.poll();
            }
            return queue.poll();
        }
    }