|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 215. Kth Largest Element in an Array |
| 4 | +# https://leetcode.com/problems/kth-largest-element-in-an-array |
| 5 | +# Medium |
| 6 | + |
| 7 | +=begin |
| 8 | +Given an integer array nums and an integer k, return the kth largest element in the array. |
| 9 | +
|
| 10 | +Note that it is the kth largest element in the sorted order, not the kth distinct element. |
| 11 | +
|
| 12 | +You must solve it in O(n) time complexity. |
| 13 | +
|
| 14 | +Example 1: |
| 15 | +Input: nums = [3,2,1,5,6,4], k = 2 |
| 16 | +Output: 5 |
| 17 | +
|
| 18 | +Example 2: |
| 19 | +Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 |
| 20 | +Output: 4 |
| 21 | +
|
| 22 | +Constraints: |
| 23 | +1 <= k <= nums.length <= 105 |
| 24 | +-104 <= nums[i] <= 104 |
| 25 | +=end |
| 26 | + |
| 27 | +# @param {Integer[]} nums |
| 28 | +# @param {Integer} k |
| 29 | +# @return {Integer} |
| 30 | +def find_kth_largest(nums, k) |
| 31 | + nums.sort[-k] |
| 32 | +end |
| 33 | + |
| 34 | +# ********************# |
| 35 | +# TEST # |
| 36 | +# ********************# |
| 37 | + |
| 38 | +require "test/unit" |
| 39 | +class Test_find_kth_largest < Test::Unit::TestCase |
| 40 | + def test_ |
| 41 | + assert_equal 5, find_kth_largest([3, 2, 1, 5, 6, 4], 2) |
| 42 | + assert_equal 4, find_kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4) |
| 43 | + end |
| 44 | +end |
| 45 | + |
| 46 | +# ********************# |
| 47 | +# Benchmark # |
| 48 | +# ********************# |
| 49 | + |
| 50 | +require "benchmark" |
| 51 | + |
| 52 | +nums = [3, 2, 3, 1, 2, 4, 5, 5, 6] |
| 53 | +k = 4 |
| 54 | +Benchmark.bm do |x| |
| 55 | + x.report("find_kth_largest: ") { find_kth_largest(nums, k) } |
| 56 | +end |
0 commit comments