Last active
July 30, 2017 21:39
-
-
Save HoangPV/493c36291413bbbb9b28395c5524542f to your computer and use it in GitHub Desktop.
check whether an array can be turn to non-descending order by a single swap 2 elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* check whether an array can be turn to non-descending order by a single swap 2 elements | |
* | |
* @param array $a | |
* @return bool | |
* @author Phan Vu Hoang <vu-hoang.phan@ekino.com> | |
*/ | |
function solution($a) | |
{ | |
$a1 = $a; | |
asort($a); | |
$flag = true; | |
foreach ($a as $key => $value) { | |
if ($value != $a1[$key]) { | |
$flag = false; | |
} | |
} | |
if ($flag) { | |
return true; | |
} else { | |
$result = array_diff_assoc($a1, $a); | |
return (count($result) == 2) ? true : false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment