記錄

[JS] 215. Kth Largest Element in an Array 본문

FRONTEND STUDY/LeetCode

[JS] 215. Kth Largest Element in an Array

prts 2022. 10. 11. 23:34

문제 링크: https://leetcode.com/problems/kth-largest-element-in-an-array/
난이도: Medium

 

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.

You must solve it in O(n) time complexity.

 

정수 배열 nums와 정수 k가 주어지면 배열에서 k번째로 큰 요소를 반환합니다.

k번째 고유 요소가 아니라 정렬된 순서에서 k번째로 가장 큰 요소라는 점에 유의하십시오.
O(n) 시간 복잡도로 풀어야 합니다.

 

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

 

Constraints:

  • 1 <= k <= nums.length <= 105
  • -104 <= nums[i] <= 104

 

문제 풀이
var findKthLargest = function(nums, k) {
    //배열에서 k번째로 큰 숫자
    //nums를 오름차순으로 sort한 뒤 index=k-1의 value를 구한다.
    return nums.sort((a,b)=>b-a)[k-1];
};

 

 

'FRONTEND STUDY > LeetCode' 카테고리의 다른 글

[JS] 34. Find First and Last Position of Element in Sorted Array  (1) 2022.10.14
[JS] 136. Single Number  (0) 2022.10.12
[JS] 7. Reverse Integer  (0) 2022.10.08
[JS] 50. Pow(x, n)  (0) 2022.10.08
[JS] 01. Two Sum  (0) 2022.10.07
Comments