我有以下JAVA程序。
private static int frogJump(int[] arrEl,int postion) {
/** Marker array for the leaf found on the way. */
boolean[] leafArray = new boolean[postion+1];
/** Total step needed for frog. */
int steps = postion;
for(int i = 0; i<arrEl.length; i++) {
/** if leaf needed for frog and it does not exist earlier. **/
if(postion>=arrEl[i] && !leafArray[arrEl[i]]) {
/* Mark leaf found */
leafArray[arrEl[i]] = true;
/** Reduce the step by one(coz one jump found). */
steps--;
}
if(steps == 0 && arrEl[i]==postion) {
return i;
}
}
return -1;
}
我想将其转换为 PHP。 到目前为止我所做的是
function solution ($A = [], $Position) {
$StonesArray = array();
$StonesArray[TRUE] = $Position + 1;
$steps = $Position;
for($i = 0; $i< count($A); $i++) {
echo "<pre>";
print_r($StonesArray);
if($Position >= $A[$i] && !$StonesArray[$A[$i]]) {
$StonesArray[$A[$i]] = true;
$steps--;
}
if($steps == 0 && $A[$i] == $Position) {
return $i;
}
}
return -1;
}
$GetSolution = solution([3,2,1], 1);
echo "<pre>";
print_r($GetSolution);
上面的程序应该返回 3。但是在我将程序转换为 PHP 语言之后,它没有返回预期的值。
我确信我已经完成了所有正确的操作,除了转换以下行
boolean[] leafArray = new boolean[postion+1];
如何用 PHP 编写这一行?
最佳答案
我刚刚把你原来的Java代码1:1翻译成PHP,大部分都可以按原样使用,几乎没有什么变化,看这个例子:
function frogJump(array $arrEl, $postion) {
/** Marker array for the leaf found on the way. */
$leafArray = array_fill(0, $postion+1, false);
/** Total step needed for frog. */
$steps = $postion;
for($i = 0; $i<count($arrEl); $i++) {
/** if leaf needed for frog and it does not exist earlier. **/
if($postion>=$arrEl[$i] && !$leafArray[$arrEl[$i]]) {
/* Mark leaf found */
$leafArray[$arrEl[$i]] = true;
/** Reduce the step by one(coz one jump found). */
$steps--;
}
if($steps == 0 && $arrEl[$i]==$postion) {
return $i;
}
}
return -1;
}
print_r(frogJump([3,2,1], 1));
输出 2
。
我还编译了Java代码,输出也是2
,所以对我来说似乎是正确的?使用 System.out.println(frogJump(new int[]{3,2,1}, 1));
关于java - 将JAVA程序转换为PHP代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45751127/