在Array Perl中查找最大值的最小值

时间:2013-09-17 07:14:43

标签: perl

我需要找出数组中出现最大值的最小值。我将这些值存储在其他数组中。

my @arr=(1,2,3,4,1,3,4,1);

1是最大值出现的最小值。

3 个答案:

答案 0 :(得分:3)

您可以使用哈希来计算每个数字的出现次数。可以发现频率最高的频率等于max频率,其中最小值可以min找到,minmax来来自List::Util

#!/usr/bin/perl

use warnings;
use strict;

use List::Util qw(min max);

my @arr = (1, 2, 3, 4, 1, 3, 4, 1);
my %occurrences;
$occurrences{$_}++ for @arr;
my $max_freq = max(values %occurrences);
print min(grep $max_freq == $occurrences{$_}, keys %occurrences);

答案 1 :(得分:2)

如果有两个或更多元素出现相同的次数,则首选更小:

my @arr=(1,2,3,4,1,3,4,1);

my %seen;
$seen{$_}++ for @arr;

my ($min_val) = sort { $seen{$b} <=> $seen{$a} || $a <=> $b } keys %seen;
print "$min_val\n";

答案 2 :(得分:0)

使用它,它将非常适合您

my @arr=(1, 2, 3, 4, 1, 3, 4, 1);
my %count;
foreach (@arr){
    $count{$_}++;
}
my ($min_by_value) = sort { $a <=> $b} keys %count;
my ($max_by_count) = sort { $count{$b} <=> $count{$a} } keys %count;
my $max =
    ($count{$min_by_value} >= $count{$max_by_count}) ? $min_by_value : $max_by_count;
print "minimum value max times = $max\n";