I have an array a = [3,6,774,24,56,2,64,56,34]
. I need to find the second largest number in a single iteration using Ruby. How do I achieve it?
我有一个数组a = [3,6,774,24,56,2,64,56,34]我需要使用Ruby在一次迭代中找到第二大数字。我如何实现它?
5 个解决方案
#1
12
Simple:
简单:
array.sort[-2]
And you're done :)
你做的:)
#2
2
sort
is probably overkill here, especially for really large arrays. Don't quite understand "single iteration", one line you mean?
这里的sort可能有点过头了,特别是对于真正的大数组。不太理解“单一迭代”,你指的是一条线?
a = [3,6,774,24,56,2,64,56,34]
b = a.shift(2).sort
c =
a.inject(b) do |(m2, m), e|
case
when e > m
[m, e]
when e > m2
[e, m]
else
[m2, m]
end
end
c.first #=> 64
#3
2
This works, but am not sure for the "single iteration"
这是可行的,但对于“单一迭代”并不确定
a.max(2)[1]
a.max(2)[1]
#4
1
Just for fun, this method gets the Nth greatest value in a enumerable (you'd use a bisect module to make the insertion into acc
more efficient). As pointed out by @Victor, you would only use it when the length of the array is much bigger than n, othersize a simple array.sort[-n]
is faster.
仅仅为了好玩,这个方法得到了一个可枚举的第n个最大的值(您将使用一个bisect模块使插入到acc更有效)。正如@Victor指出的,只有当数组的长度比n大得多时,才会使用它,而不是简单数组的大小。[n]更快。
module Enumerable
def max_nth(n)
inject([]) do |acc, x|
(acc + [x]).sort[[acc.size-(n-1), 0].max..-1]
end.first
end
end
p [1, 5, 2, 32, 2, 41, 15, 55].max_nth(2) #=> 41
#5
0
It works too:
它的工作原理:
arr.sort.reverse[1]
#1
12
Simple:
简单:
array.sort[-2]
And you're done :)
你做的:)
#2
2
sort
is probably overkill here, especially for really large arrays. Don't quite understand "single iteration", one line you mean?
这里的sort可能有点过头了,特别是对于真正的大数组。不太理解“单一迭代”,你指的是一条线?
a = [3,6,774,24,56,2,64,56,34]
b = a.shift(2).sort
c =
a.inject(b) do |(m2, m), e|
case
when e > m
[m, e]
when e > m2
[e, m]
else
[m2, m]
end
end
c.first #=> 64
#3
2
This works, but am not sure for the "single iteration"
这是可行的,但对于“单一迭代”并不确定
a.max(2)[1]
a.max(2)[1]
#4
1
Just for fun, this method gets the Nth greatest value in a enumerable (you'd use a bisect module to make the insertion into acc
more efficient). As pointed out by @Victor, you would only use it when the length of the array is much bigger than n, othersize a simple array.sort[-n]
is faster.
仅仅为了好玩,这个方法得到了一个可枚举的第n个最大的值(您将使用一个bisect模块使插入到acc更有效)。正如@Victor指出的,只有当数组的长度比n大得多时,才会使用它,而不是简单数组的大小。[n]更快。
module Enumerable
def max_nth(n)
inject([]) do |acc, x|
(acc + [x]).sort[[acc.size-(n-1), 0].max..-1]
end.first
end
end
p [1, 5, 2, 32, 2, 41, 15, 55].max_nth(2) #=> 41
#5
0
It works too:
它的工作原理:
arr.sort.reverse[1]