Skip to content

Commit 7e9fe72

Browse files
authored
2024-12-24 v. 7.4.6: added "692. Top K Frequent Words"
2 parents f6d3b53 + 6ed1387 commit 7e9fe72

File tree

4 files changed

+50
-1
lines changed

4 files changed

+50
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,3 +610,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
610610
| 677. Map Sum Pairs | [Link](https://leetcode.com/problems/map-sum-pairs/) | [Link](./lib/medium/677_map_sum_pairs.rb) | [Link](./test/medium/test_677_map_sum_pairs.rb) |
611611
| 678. Valid Parenthesis String | [Link](https://leetcode.com/problems/valid-parenthesis-string/) | [Link](./lib/medium/678_valid_parenthesis_string.rb) | [Link](./test/medium/test_678_valid_parenthesis_string.rb) |
612612
| 687. Longest Univalue Path | [Link](https://leetcode.com/problems/longest-univalue-path/) | [Link](./lib/medium/687_longest_univalue_path.rb) | [Link](./test/medium/test_687_longest_univalue_path.rb) |
613+
| 692. Top K Frequent Words | [Link](https://leetcode.com/problems/top-k-frequent-words/) | [Link](./lib/medium/692_top_k_frequent_words.rb) | [Link](./test/medium/test_692_top_k_frequent_words.rb) |

leetcode-ruby.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '7.4.5'
8+
s.version = '7.4.6'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
1111
s.executable = 'leetcode-ruby'
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# frozen_string_literal: true
2+
3+
# https://leetcode.com/problems/top-k-frequent-words/
4+
# @param {String[]} words
5+
# @param {Integer} k
6+
# @return {String[]}
7+
def top_k_frequent_words(words, k)
8+
values = words.each_with_object(::Hash.new(0)) { |e, total| total[e] += 1; }
9+
10+
to_sort = values.to_a
11+
to_sort.sort! do |a, b|
12+
diff = b[1] - a[1]
13+
if diff.zero?
14+
a[0] <=> b[0]
15+
else
16+
diff
17+
end
18+
end
19+
20+
to_sort[0...k].map(&:first)
21+
end
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/medium/692_top_k_frequent_words'
5+
require 'minitest/autorun'
6+
7+
class TopKFrequentWordsTest < ::Minitest::Test
8+
def test_default_one
9+
assert_equal(
10+
%w[i love],
11+
top_k_frequent_words(
12+
%w[i love leetcode i love coding],
13+
2
14+
)
15+
)
16+
end
17+
18+
def test_default_two
19+
assert_equal(
20+
%w[the is sunny day],
21+
top_k_frequent_words(
22+
%w[the day is sunny the the the sunny is is],
23+
4
24+
)
25+
)
26+
end
27+
end

0 commit comments

Comments
 (0)