鳕鱼运动:鱼

时间:2020-06-04 08:46:08

标签: javascript algorithm

任务:无数条令人讨厌的鱼在河上流动。计算有多少条鱼还活着。 Here is description of exercise.
我使用javascript,我的代码如下:

// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');

//fish
function solution(fishSize, fishDirection)
{
    var arr = [];
    // arr.push({size: fishSize[0], direction: fishDirection[0]});
    // for(let i = 1; i < fishSize.length; i++)
    // {
    //     pushNewFish(arr, fishSize[i], fishDirection[i]);
    // }
    for (let i = fishSize.length - 1; i >= 0; i--)
    {
        pushNewFish(arr, fishSize[i], fishDirection[i]);
    }

    return arr.length;
}

function pushNewFish(arr, fishSize, fishDirection)
{
    // if(arr.length > 0 && fishDirection != arr[arr.length - 1].fishDirection && fishSize != arr[arr.length - 1].fishSize)
    if(arr.length > 0 && arr[arr.length - 1].fishDirection === 0 && fishDirection === 1 && fishSize != arr[arr.length - 1].fishSize)
    {
        // while(arr.length > 0 && arr[arr.length - 1].fishDirection != fishDirection)
        while(arr.length > 0 && arr[arr.length - 1].fishDirection === 0 && fishDirection === 1)
        {
            if (arr[arr.length - 1].fishSize < fishSize)
            {
                arr.pop();
            }
            else 
            {
                if(arr[arr.length - 1].fishSize === fishSize)
                {
                    arr.push({fishSize, fishDirection});
                }
                break;
            }
        }
        if (arr.length == 0) arr.push({fishSize, fishDirection});
    }
    else 
    {
        arr.push({fishSize: fishSize, fishDirection: fishDirection});
    }
}

我的代码仅获得50%的任务分数。我不明白为什么我的代码没有通过所有测试。请帮助我找到错误,谢谢!

1 个答案:

答案 0 :(得分:0)

function solution(A, B) {
// write your code in JavaScript (Node.js 8.9.4)
let stack=[];
 let c=B.length;
 for(let j=0;j<B.length;j++){
   if(B[j]===1){
     stack.push(A[j]);
   }
   else if(B[j]===0){
    while(stack.length>0){
        if(stack[stack.length-1]>A[j]){
           c=c-1;
          break;
        }else if(stack[stack.length-1]<A[j]){
           c=c-1;
          stack.pop();
        }
    }
   }
 }
 return c;
}