我想找到数组中四个最大元素中每个元素的索引。
注意: - 我需要的是我不需要对它们进行排序的元素的位置。
答案 0 :(得分:1)
循环通过它们并跟踪四个最大的是唯一的方法。我想不出比O(n)操作更有效的东西。
我认为这会奏效。它将为您提供一个包含可变数量的最大索引的数组:
Function GetLargestIndices(inArray() As Integer, numIndices As Integer) As Integer()
ReDim returnArray(numIndices) As Integer
Dim i As Integer
Dim j As Integer
Dim k As Integer
For i = 0 To UBound(returnArray)
returnArray(i) = -1
Next
For i = 0 To UBound(inArray)
For j = UBound(returnArray) To 0 Step -1
If (returnArray(j) = -1) Then
returnArray(j) = i
Exit For
ElseIf (inArray(i) > inArray(returnArray(j))) Then
If (j > 0) Then
For k = 0 To j
returnArray(k) = returnArray(k + 1)
Next
End If
returnArray(j) = i
Exit For
End If
Next
Next
GetLargestIndices = returnArray
End Function
以下是测试它的方法:
Sub Test()
Dim testArray(10) As Integer
testArray(0) = 125
testArray(1) = 6
testArray(2) = 45
testArray(3) = 15
testArray(4) = 16
testArray(5) = 107
testArray(6) = 108
testArray(7) = 10
testArray(8) = 32
testArray(9) = 45
testArray(10) = 72
Dim largestArray() As Integer
largestArray = GetLargestIndices(testArray, 4)
End Sub