我有一个整数数组,我需要知道最大数字的索引(不是实际值,只是最高的索引)。获取数组中最大整数的索引
但是,如果一个或多个索引“绑定”最高值,我需要拥有所有分享该高价值的索引。
我认为这个函数需要返回一个数组(因为它可能是一个或多个索引),但我不完全知道如何去获得更高效的解决方案。
我有一个整数数组,我需要知道最大数字的索引(不是实际值,只是最高的索引)。获取数组中最大整数的索引
但是,如果一个或多个索引“绑定”最高值,我需要拥有所有分享该高价值的索引。
我认为这个函数需要返回一个数组(因为它可能是一个或多个索引),但我不完全知道如何去获得更高效的解决方案。
如果这将是一件普通的事情,您可以编写自己的扩展。你应该添加一些额外的理智/ null的检查,但是这将让你开始:
Module Extensions
<System.Runtime.CompilerServices.Extension()> Function FindAllIndexes(Of T)(ByVal array() As T, ByVal match As Predicate(Of T)) As Integer()
''//Our return object
Dim Ret As New List(Of Integer)
''//Current array index
Dim I As Integer = -1
''//Infinite loop, break out when we no more matches are found
Do While True
''//Loop for a match based on the last index found, add 1 so we dont keep returning the same value
I = System.Array.FindIndex(array, I + 1, match)
''//If we found something
If I >= 0 Then
''//Append to return object
Ret.Add(I)
Else
''//Otherwise break out of loop
Exit Do
End If
Loop
''//Return our array
Return Ret.ToArray()
End Function
End Module
然后调用它:
Dim ints As Integer() = New Integer() {1, 2, 8, 6, 8, 1, 4}
Dim S = ints.FindAllIndexes(Function(c) c = ints.Max())
''//S now holds 2 and 4
IList中有一个成员的IndexOf,这有助于。此代码完全未经测试,可能至少有一个错误。
Public Function GetPostionsOfMaxValue(ByVal input() As Integer) As Integer()
Dim ints = New List(Of Integer)(input)
Dim maxval = ints.Max
Dim indexes As New List(Of Integer)
Dim searchStart As Integer = 0
Do Until searchStart >= ints.Count
Dim index = ints.IndexOf(maxval, searchStart)
If index = -1 Then Exit Do
indexes.Add(index)
searchStart = index + 1
Loop
Return indexes.ToArray
End Function
这工作像一个魅力。谢谢! – 2011-05-24 22:01:25