Skip to content

Commit

Permalink
Merge pull request #185 from fartem/703_Kth_Largest_Element_in_a_Stream
Browse files Browse the repository at this point in the history
2023-08-01 v. 1.3.6: added "703. Kth Largest Element in a Stream"
  • Loading branch information
fartem authored Aug 1, 2023
2 parents b82f7a9 + 39617e0 commit 1e714f5
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,3 +141,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
| 682. Baseball Game | [Link](https://leetcode.com/problems/baseball-game/) | [Link](./lib/easy/682_baseball_game.rb) |
| 693. Binary Number with Alternating Bits | [Link](https://leetcode.com/problems/binary-number-with-alternating-bits/) | [Link](./lib/easy/693_binary_number_with_alternating_bits.rb) |
| 700. Search in a Binary Search Tree | [Link](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [Link](./lib/easy/700_search_in_a_binary_search_tree.rb) |
| 703. Kth Largest Element in a Stream | [Link](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | [Link](./lib/easy/703_kth_largest_element_in_a_stream.rb) |
2 changes: 1 addition & 1 deletion leetcode-ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ require 'English'
::Gem::Specification.new do |s|
s.required_ruby_version = '>= 3.0'
s.name = 'leetcode-ruby'
s.version = '1.3.5'
s.version = '1.3.6'
s.license = 'MIT'
s.files = ::Dir['lib/**/*.rb'] + %w[bin/leetcode-ruby README.md LICENSE]
s.executable = 'leetcode-ruby'
Expand Down
22 changes: 22 additions & 0 deletions lib/easy/703_kth_largest_element_in_a_stream.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# frozen_string_literal: true

# https://leetcode.com/problems/kth-largest-element-in-a-stream/
class KthLargest
# @param {Integer} k
# @param {Integer[]} nums
def initialize(k, nums)
@k = k
@a = nums.sort.reverse.first(k)
end

# @param {Integer} val
# @@return {Integer}
def add(val)
if @a.size < @k || val > @a.last
@a.insert(@a.bsearch_index { |v| val >= v } || -1, val)
@a.pop if @a.size > @k
end

@a.last
end
end
17 changes: 17 additions & 0 deletions test/easy/test_703_kth_largest_element_in_a_stream.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# frozen_string_literal: true

require_relative '../test_helper'
require_relative '../../lib/easy/703_kth_largest_element_in_a_stream'
require 'minitest/autorun'

class KthLargestElementInAStreamTest < ::Minitest::Test
def test_default
kth_largest = ::KthLargest.new(3, [4, 5, 8, 2])

assert_equal(4, kth_largest.add(3))
assert_equal(5, kth_largest.add(5))
assert_equal(5, kth_largest.add(10))
assert_equal(8, kth_largest.add(9))
assert_equal(8, kth_largest.add(4))
end
end

0 comments on commit 1e714f5

Please sign in to comment.