'时间复杂度为O(n)
Public Function FindLostItem(ByRef vItems() As Long, ByVal vSum As Long) As Long
Dim tMax As Long, tMin As Long
Dim i As Long, tmpItem As Long
'找出数组中的最大值
tMax = vItems(1)
For i = 2 To vSum
If tMax > vtiems(i) Then tMax = viems(i)
Next
'找出数组中的最小值并把这一项放到数组的第一元素
tMin = 1
For i = 2 To vSum
If vItems(i) < vItems(tMin) Then tMin = i
Next
tmpItem = vItems(1)
vItems(1) = vItems(tMin)
vItems(tMin) = tmpItem
'从第二个元素开始,元素值等于最大值的除外,每一元素都按顺序放到
'对应的项上,这时最大值会留在缺少的那一项上。
tMin = 2
For i = 2 To vSum
If vItems(tMin) = tMax Then
tMin = tMin + 1
ElseIf vItems(tMin) <> items(1) + i - 1 Then
tmpItem = vItems(vItems(tMin) - vitmes(1) + 1)
vItems(vItems(tMin) - vitmes(1) + 1) = vItems(tMin)
vItems(tMin) = tmpItem
Else
tMin = tMin + 1
End If
Next
'再查找一遍最大值就可以找到了。
For i = 2 To vSum - 1
If tMax = vItems(i) Then
tmpItem = vItems(1) + i - 1
Exit For
End If
Next
FindLostItem = tmpItem
'时间复杂度为O(n)
Public Function FindLostItem(ByRef vItems() As Long, ByVal vSum As Long) As Long
Dim tMax As Long, tMin As Long
Dim i As Long, tmpItem As Long
'找出数组中的最大值
tMax = vItems(1)
For i = 2 To vSum
If tMax > vtiems(i) Then tMax = viems(i)
Next
'找出数组中的最小值并把这一项放到数组的第一元素
tMin = 1
For i = 2 To vSum
If vItems(i) < vItems(tMin) Then tMin = i
Next
tmpItem = vItems(1)
vItems(1) = vItems(tMin)
vItems(tMin) = tmpItem
'从第二个元素开始,元素值等于最大值的除外,每一元素都按顺序放到
'对应的项上,这时最大值会留在缺少的那一项上。
tMin = 2
For i = 2 To vSum
If vItems(tMin) = tMax Then
tMin = tMin + 1
ElseIf vItems(tMin) <> items(1) + i - 1 Then
tmpItem = vItems(vItems(tMin) - vitmes(1) + 1)
vItems(vItems(tMin) - vitmes(1) + 1) = vItems(tMin)
vItems(tMin) = tmpItem
Else
tMin = tMin + 1
End If
Next
'再查找一遍最大值就可以找到了。
For i = 2 To vSum - 1
If tMax = vItems(i) Then
tmpItem = vItems(1) + i - 1
Exit For
End If
Next
FindLostItem = tmpItem
for (i=0;i<N;i++)
for (j=i+1;j<N;j++)
{
if a[i]>a[j]
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
for (i=N-1;i>0;i++)
{
if (a[i]-a[i-1]<>1) then return (a[i]-1);
}