如何找到数组中第二大元素的索引?

我正在使用Ruby 2.4,我有一组数字:

[23423, 349843, 13123, 29239, 20201, ...] 

如何找到与数组中第二大值对应的数组索引? 您可以假设数组中至少有两个元素。

试试这个。 a是你的arrays

 a.index(a.max(2).last) 
 a = [1,3,1,2] 

11被认为是a的两个最小值时

 def second_largest_not_uniq(a) a.each_index.min_by(2) { |i| a[i] }[1] end second_largest_not_uniq [1,3,1,2] #=> 2 second_largest_not_uniq [1] #=> nil second_largest_not_uniq [] #=> nil 

12被认为是a的两个最小值时

 def second_largest_uniq(a) a.each_index.to_a.uniq { |i| a[i] }.min_by(2) { |i| a[i] }[1] end second_largest_uniq [1,3,1,2] #=> 3 second_largest_uniq [1,1,1] #=> nil second_largest_uniq [] #=> nil second_largest_uniq [1] #=> nil 

如果您需要该值,请尝试此操作

 value = array.max(2).last 

如果您需要索引,请尝试此操作

 index = array.each_with_index.max_by(2, &:first).last.last 

这是如何运作的?

  • each_with_index创建一个元组为[element, index]的枚举器
  • max_by(2, &:first)找到两个最大的元组,比较它们的第一个值,即元素
  • last获得第二大元组
  • last通过获取最后一个值即索引来解包该元组

注意,这会创建O(n)临时数组,因为我们链接了each_with_index枚举器,我不会将它用于性能关键代码路径中的大型数组。

我对数组进行排序然后使用类似的东西:

 ary.size - 2 

例如:

 ary = 5.times.map{ rand(100) } # => [61, 75, 35, 48, 59] ary.sort # => [35, 48, 59, 61, 75] ary.sort[-2] # => 61 ary.size - 2 # => 3 ary.sort[ary.size - 2] # => 61 

这不会返回原始数组中元素的索引。

排序后第二大元素的索引始终为array.size - 2

如果数组必须按其原始顺序,我会这样做:

 ary = 5.times.map{ rand(100) } # => [83, 72, 4, 63, 68] hash = ary.each_with_index.to_h # => {83=>0, 72=>1, 4=>2, 63=>3, 68=>4} hash.sort[-2] # => [72, 1] 

此时, hash.sort[-2]返回原始数组中的值及其索引。 72是值, ary[1]是值的索引。