迭代具有多行国家/地区的文件并以最多出现的国家/地区打印出来的最佳算法/方法是什么?
每行都是一个字符串,每行只包含一个国家/地区名称.
假设可能有10亿个不同的国家.(国家是个坏榜样)
United States
Iran
India
United States
China
Iran
....
....
Canada //1 billionth line
Run Code Online (Sandbox Code Playgroud)
# Count the unique elements.
my %hash;
while(<>) {
chomp;
$hash{$_}++;
}
# Find the key with the largest value.
sub largest_value {
my $hash = shift;
my ($big_key, $big_val) = each %$hash;
while (my ($key, $val) = each %$hash) {
if ($val > $big_val) {
$big_key = $key;
$big_val = $val;
}
}
return $big_key;
}
print largest_value(\%hash);
Run Code Online (Sandbox Code Playgroud)