Interview - Find magnitude pole in an array

前端 未结 8 2401
孤独总比滥情好
孤独总比滥情好 2021-02-09 15:52

Magnitude Pole: An element in an array whose left hand side elements are lesser than or equal to it and whose right hand side element are greater than or equal to it.

8条回答
  •  半阙折子戏
    2021-02-09 16:28

    I saw this problem on Codility, solved it with Perl:

    sub solution {
            my (@A) = @_;            
    
            my ($max, $min) = ($A[0], $A[-1]);
            my %candidates;
    
            for my $i (0..$#A) {
                    if ($A[$i] >= $max) {
                            $max = $A[$i];
                            $candidates{$i}++;
                    }
            }
            for my $i (reverse 0..$#A) {
                    if ($A[$i] <= $min) {
                            $min = $A[$i];
                            return $i if $candidates{$i};
                    }
            }
            return -1;
    }
    

提交回复
热议问题