算法复杂度是O(N) 例如 {8} :True {8, 1 } :True {8, 1, 2}:False {8, 1, 2, 1,9}:true {8, 1, 2, 1, 2, 9}:False Private Function solution(ByVal arr As Integer()) As Boolean Dim swapCount As Integer = 0 For big As Integer = 0 To arr.Length - 2 If arr(big) > arr(big + 1) Then If swapCount > 0 Then '交换过一次了,不能再交换了。 Return False End If '查找能够交换的数字 Dim blnFoundSmall As Boolean = False For small As Integer = arr.Length - 1 To big + 1 Step -1 If arr(small) < arr(big) _ AndAlso arr(big) >= arr(small - 1) AndAlso (small = arr.Length-1 OrElse arr(big) <= arr(small + 1)) _ AndAlso arr(small) <= arr(big + 1) AndAlso (big = 0 OrElse arr(small) >= arr(big - 1)) Then blnFoundSmall = True '找到了 swap(arr, big, small) '交换 swapCount += 1 '交换次数加1 Exit For End If Next If blnFoundSmall = False Then '找不到的话不能交换。 Return False End If End If Next Return True End Function Private Sub swap(ByRef rArr As Integer(), ByVal IdxA As Integer, ByVal IdxB As Integer) Dim temp = rArr(IdxA) rArr(IdxA) = rArr(IdxB) rArr(IdxB) = temp End Sub
例如
{8} :True
{8, 1 } :True
{8, 1, 2}:False
{8, 1, 2, 1,9}:true
{8, 1, 2, 1, 2, 9}:False
Private Function solution(ByVal arr As Integer()) As Boolean
Dim swapCount As Integer = 0 For big As Integer = 0 To arr.Length - 2
If arr(big) > arr(big + 1) Then
If swapCount > 0 Then
'交换过一次了,不能再交换了。
Return False
End If '查找能够交换的数字
Dim blnFoundSmall As Boolean = False
For small As Integer = arr.Length - 1 To big + 1 Step -1
If arr(small) < arr(big) _
AndAlso arr(big) >= arr(small - 1) AndAlso (small = arr.Length-1 OrElse arr(big) <= arr(small + 1)) _
AndAlso arr(small) <= arr(big + 1) AndAlso (big = 0 OrElse arr(small) >= arr(big - 1)) Then
blnFoundSmall = True '找到了
swap(arr, big, small) '交换
swapCount += 1 '交换次数加1
Exit For
End If
Next If blnFoundSmall = False Then
'找不到的话不能交换。
Return False
End If
End If
Next Return True
End Function Private Sub swap(ByRef rArr As Integer(), ByVal IdxA As Integer, ByVal IdxB As Integer)
Dim temp = rArr(IdxA)
rArr(IdxA) = rArr(IdxB)
rArr(IdxB) = temp
End Sub