110,539
社区成员
发帖
与我相关
我的任务
分享
function solution($A) {
// write your code in PHP5.3
$arr = array();
$len = count($A);
$check = false;
for ($i=0;$i<$len-1;$i++)
{
for ($j=$i+1;$j<$len;$j++)
{
$arr = $A;
$temp = $arr[$j];
$arr[$j] = $arr[$i];
$arr[$i] = $temp;
$no_decrease = true;
for ($k=1;$k< $len;$k++)
{
if ($arr[$k]<$arr[$k-1])
{
$no_decrease = false;
}
}
if ($no_decrease == true)
{
$check = true;
}
}
}
return $check;
}
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