Skip to content

Commit 83f1bbb

Browse files
committed
215. Kth Largest Element in an Array
1 parent 0edce3e commit 83f1bbb

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@
7474
| 208 | Implement Trie (Prefix Tree) | [Ruby](./algorithms/ruby/0208-implement-trie-prefix-tree.rb) | Medium |
7575
| 210 | Course Schedule II | [Ruby](./algorithms/ruby/0210-course-schedule-ii.rb) | Medium |
7676
| 211 | Design Add and Search Words Data Structure | [Ruby](./algorithms/ruby/0211-design-add-and-search-words-data-structure.rb) | Medium |
77+
| 215 | Kth Largest Element in an Array | [Ruby](./algorithms/ruby/0215-kth-largest-element-in-an-array.rb) | Medium |
7778
| 226 | Invert Binary Tree | [Ruby](./algorithms/ruby/0226-invert-binary-tree.rb) | Easy |
7879
| 227 | Basic Calculator II | [Ruby](./algorithms/ruby/0227-basic-calculator-ii.rb) | Medium |
7980
| 230 | Kth Smallest Element in a BST | [Ruby](./algorithms/ruby/0230-kth-smallest-element-in-a-bst.rb) | Medium |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)