鱼鳕鱼运动

时间:2017-01-31 21:17:43

标签: php algorithm stack time-complexity

尝试解决关于codility fish challenge的这一挑战我无法理解为什么我的代码不会传递所有测试。

function solution($A, $B) {
  // write your code in PHP7.0
  $stack =[];

  foreach($A as $key =>$value) {
    if(empty($stack)){
      array_push($stack,$key);
    }
    else if($B[count($stack)-1] == 1 && $B[$key]==0 )
    {
      if($value > $A[count($stack)-1])
      {
        array_pop($stack);
        array_push($stack,$key);
      }
    }
    else array_push($stack,$key);
  }
  return count($stack);
}

3 个答案:

答案 0 :(得分:1)

您的代码有两个问题。

  1. 该代码未正确引用堆栈中的项目。使用$B[$stack[count($stack)-1]]代替$B[count($stack)-1]。使用$A[$stack[count($stack)-1]]而不是$A[count($stack)-1]

  2. 上游鱼类必须与每条下游鱼类竞争,而不仅仅是它们遇到的第一条鱼类。

以下是成功的解决方案:

function solution($A, $B) {
  // write your code in PHP7.0
  $stack = [];
  $key = 0;
  while($key < count($A)) {
    if(empty($stack)){
      array_push($stack,$key);
      $key++;
    }
    else if($B[$stack[count($stack)-1]] == 1 && $B[$key] == 0){
      if($A[$key] > $A[$stack[count($stack)-1]])
      {
        // fish going upstream eats fish going downstream
        array_pop($stack);
      } else {
        // fish going downstream eats fish going upstream
        $key++;
      }
    }
    else {
      array_push($stack,$key);
      $key++;
    }
  }
  return count($stack);
}

答案 1 :(得分:0)

得分为100%的Python解决方案

def solution(A, B):
    ds = []
    up = 0

    for i in range(len(A)):
        if B[i] == 1:
            ds.append(A[i])
        if B[i] == 0:
            if len(ds) == 0:
                up += 1
                continue
            while (len(ds) > 0):
                ele = ds.pop()
                if ele < A[i]:
                    continue
                else:
                    ds.append(ele)
                    break
            if len(ds) == 0:
                up += 1
    return len(ds) + up

答案 2 :(得分:-1)

试试这个:

  function solution($A, $B) {
  // write your code in PHP7.0
  $stack =[];

  foreach($A as $key =>$value) {
    if(empty($stack)){
      array_push($stack,$key);
    }
    else if($B[count($stack)-1] == 1 && $B[$key]==0 )
    {
        while(true) {
          if($value > $A[count($stack)-1] && !empty($stack) && $B[count($stack)-1] == 1)
          {
            array_pop($stack);
          }
          else break;
        }
      array_push($stack,$key);
    }
    else array_push($stack,$key);
  }
  return count($stack);

}