问题
I'm using Ruby 2.4 and I have an array of numbers:
[23423, 349843, 13123, 29239, 20201, ...]
How can I find the array index corresponding to the second greatest value in the array? You can assume that there are at least two elements in the array.
回答1:
Try this one. a
is your array
a.index(a.max(2).last)
回答2:
a = [1,3,1,2]
When 1
and 1
are regarded as the two smallest values of 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
When 1
and 2
are regarded as the two smallest values of 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
回答3:
Try this if you need the value
value = array.max(2).last
Try this if you need the index
index = array.each_with_index.max_by(2, &:first).last.last
How does this work?
each_with_index
creates an enumerator with tuples of[element, index]
max_by(2, &:first)
finds the two greatest tuples, comparing their first value aka the elementlast
gets the second-greatest tuplelast
unpacks that tuple by getting last value aka the index
Note, this creates O(n)
temporary arrays though because we chain the each_with_index
enumerator and I would not use this for large arrays in a performance critical codepath.
回答4:
I'd sort the array then use something like:
ary.size - 2
For instance:
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
This does not return the index of the element in the original array.
The index of the second largest element after sorting is always array.size - 2
.
If the array has to be in its original order I'd do this:
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]
At that point hash.sort[-2]
returns the value and its index in the original array. 72
is the value and ary[1]
is the index to the value.
来源:https://stackoverflow.com/questions/41703164/how-can-i-find-the-index-of-the-second-greatest-element-in-my-array