首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取数组中最小非负数的索引?

获取数组中最小非负数的索引?
EN

Stack Overflow用户
提问于 2018-07-01 06:19:48
回答 3查看 178关注 0票数 0

我有一个数组,看起来像这样

@array = ('3', '4', '71', '1', '-598', '-100203');

我想找出数组中整数中最小的非负数的索引。

对于这种情况:

  • 最小非负数=1最小非负数的
  • 索引= 3
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-07-01 08:06:56

你想要对数(O(N)),而不是sort (O(N reduce N))!

use List::Util qw( reduce );

my $i =
   reduce { $array[$a] <= $array[$b] ? $a : $b }
      grep { $array[$_] >= 0 }
         0..$#array;

如果你想要最优的性能,下面的内容会让你更接近:

use Config     qw( %Config );
use List::Util qw( minstr );

my $i =
   unpack "x$Config{ivsize} J",
      minstr
         map { pack 'J> J', $array[$_], $_ }
            grep { $array[$_] >= 0 }
               0..$#array;
票数 5
EN

Stack Overflow用户

发布于 2018-07-01 06:41:56

诀窍是对索引号列表进行排序,然后选择第一个:

my $ix = (sort { $array[$a]) <=> $array[$b] } grep { $array[$_] >= 0 } 0..$#array)[0];
票数 1
EN

Stack Overflow用户

发布于 2018-07-01 20:08:30

最快的方法是扫描列表。

#!/usr/bin/env perl

# always use these two
use strict;
use warnings;

use feature qw( :all );

# --------------------------------------
#       Name: smallest_whole_number
#      Usage: ( $smallest, $index ) = smallest_whole_number( @array );
#    Purpose: Find the smallest whole number in an array.
# Parameters: @array -- array of integers
#    Returns: ( $smallest, $index ) unless exception.
#             ( -1, -1 ) if exception.
#
sub smallest_whole_number {
    my @array = @_;

    # check if array empty
    return ( -1, -1 ) unless @array;

    # scan for first whole number
    my $index = 0;
    while( $array[$index] < 0 ){

        # exception if no whole numbers in array
        return ( -1, -1 ) if $index >= $#array;

        $index ++;
    }

    # save first whole number found
    my $smallest = $array[$index];

    # scan the rest of the array
    for( my $i = $index + 1; $i <= $#array; $i ++ ){
        my $nbr = $array[$i];

        # skip negative numbers
        next if $nbr < 0;

        # check if current number smaller
        if( $smallest > $nbr ){
            $smallest = $nbr;
            $index    = $i;
        }
    }

    return ( $smallest, $index );
}

# --------------------------------------
# main

my @array = ('3', '4', '71', '1', '-598', '-100203');

my ( $smallest, $index ) = smallest_whole_number( @array );
say "smallest is $smallest at index $index";
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51118962

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档