배열에서 K번째로 큰 요소
Kth Largest Element in an Array - LeetCode
Can you solve this real interview question? 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 eleme
leetcode.com
정수 배열 nums과 정수가 주어 지면 배열에서 가장 큰 요소를 반환k 합니다 . kth
이는 개별 요소 가 아니라 정렬된 순서에서 가장 큰 요소 입니다 .kthkth
정렬하지 않고 해결할 수 있나요?
예시 1:
입력: nums = [3,2,1,5,6,4], k = 2
출력: 5
예 2:
입력: nums = [3,2,3,1,2,4,5,5,6], k = 4
출력: 4
제약:
- 1 <= k <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
문제풀이
class Solution {
public int findKthLargest(int[] nums, int k) {
Arrays.sort(nums);
return nums[nums.length-k];
}
}
int[] nums를 Arrays.sort()로 오름차순으로 정렬후에
k번째로 큰요소를 해석하면, 뒤에서부터 k번째 즉, num.length-k가 된다
그리하여 nums[nums.length-k]를 반환하여 k번째로 큰 수를 구하였다.
'알고리즘' 카테고리의 다른 글
[Graph] Clone Graph (0) | 2023.09.14 |
---|---|
[Trie] Implement Trie (Prefix Tree) (0) | 2023.09.11 |
[BFS] Average of Levels in Binary Tree (0) | 2023.09.08 |
[leetCode] Kth Smallest Element in a BST (0) | 2023.09.08 |
[Binary Search] Find Minimum in Rotated Sorted Array (0) | 2023.09.04 |