Codility标记javascript解决方案

时间:2015-06-20 15:41:42

标签: javascript

Codility标志挑战(在这里查看其他帖子,但它没有帮助)

以下代码获得40%,并且在中等和大输入上失败。输入大小可能并不重要,但在那些输入中是一些特殊情况,我的代码失败,我无法找出这些情况。

这是任务https://codility.com/programmers/lessons/8

以下是我的结果https://codility.com/demo/results/demoZHJB56-RHM/

function solution(A)
{
    var mountains = A.length;
    var prevMountain;
    var currentMountain;
    var nextMountain;
    var i;  
    var peaks = []; 
    var currentPeak;
    var prevPeak; 
    var output = 0;
    var gap;

    for(i = 1; i < (A.length-1); i++)
    {                      
        prevMountain = A[i-1];
        currentMountain = A[i];
        nextMountain = A[i+1];

        if(currentMountain > prevMountain && currentMountain > nextMountain)
        {
            peaks.push(i);
        }                                                                                                                
    }                                                                                                                     

    if(peaks.length > 0)
    {
        gap = peaks.length;                                                                                                                
        for(i = peaks.length; i >= 1; i--)
        {                                                     
            currentPeak = peaks[i-1];
            prevPeak = peaks[i-2];

            if(i === 1){ prevPeak = peaks.length * (-1); }                          

            if((currentPeak - prevPeak) < gap)
            {                             
                gap = gap - 1;
                peaks[i-2] = currentPeak;
                peaks[i-1] = prevPeak;               
            }
            else
            {
                output++;               
            }      
        }
    }
  return output;
}   

1 个答案:

答案 0 :(得分:0)

问题是我在洗牌后没有重置循环,

这是我的100%[O(N)或O(N * sqrt(N))] javascript解决方案 - &gt;

https://codility.com/demo/results/demoPA5GDW-Y7R/