How to find the index of the second largest element in my array?

I am using Ruby 2.4 and I have an array of numbers:

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

How can I find the index of the array corresponding to the second highest value in the array? You can assume that there are at least two elements in the array.

0
source share
4 answers

Try it. a- your array

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

When 1and are 1considered as the two smallest valuesa

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 

When 1and are 2considered as the two smallest valuesa

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
+1
source

,

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 , aka index

, O(n), - , each_with_index, .

0

, - :

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] - .

-1

Source: https://habr.com/ru/post/1667906/


All Articles