• 主页

# 诚征大神求解codility上的测试题，智力和能力大考验！（我是被打击惨了，看看大神们如何吧）

A non-empty zero-indexed array A consisting of N integers is given.

You can perform a single swap operation in array A. This operation takes two indices I and J, such that 0 ≤ I ≤ J < N, and exchanges the values of A[I] and A[J].

The goal is to check whether array A can be sorted into non-decreasing order by performing only one swap operation.

For example, consider array A such that:

A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 3
A[4] = 7
After exchanging the values A[2] and A[3] we obtain an array [1, 3, 3, 5, 7], which is sorted in non-decreasing order.

Write a function:

function solution(\$A);

that, given a non-empty zero-indexed array A consisting of N integers, returns true if the array can be sorted into non-decreasing order by one swap operation or false otherwise.

For example, given:

A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 3
A[4] = 7
the function should return true, as explained above.

On the other hand, for the following array:

A[0] = 1
A[1] = 3
A[2] = 5
A[3] = 3
A[4] = 4
the function should return false, as there is no single swap operation that sorts the array.

Assume that:

N is an integer within the range [1..100,000];
each element of array A is an integer within the range [1..1,000,000,000].
Complexity:

expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

``````
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;

}
``````

...全文
459 点赞 收藏 3

3 条回复

geyewei 2014年10月03日

``````    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
``````

C#

8.4w+

64.0w+

.NET技术 C#