IはCodility Peak problemに取り組んでいます:CodilityピークJavaScript実装
分割インデックスPようA [Pことを含むべきそれぞれが同じサイズのブロックの最大数に配列 - A] [P + 1]を含む。
私のソリューションは以下のとおりですが、得点は45%です。だから私の質問は:
私はまだ解決策を改善することができますか?
function solution(A) {
var storage = [], counter = 0;
// 1. So first I used a loop to find all the peaks
// and stored them all into an array called storage
for(var i = 1; i < A.length - 1; i++) {
if (A[i] > A[i-1] && A[i] > A[i+1]) {
storage.push(i);
}
}
// 2. Go and write the function canBeSeparatedInto
// 3. Use the for loop to check the counter
for(var j = 1; j < A.length; j++) {
if (canBeSeparatedInto(j, A, storage)) {
counter = j;
}
}
return counter;
}
/* this function tells if it is possible to divide the given array into given parts
* we will be passing our function with parameters:
* @param parts[number]: number of parts that we intend to divide the array into
* @param array[array]: the original array
* @param peaks[array]: an storage array that store all the index of the peaks
* @return [boolean]: true if the given array can be divided into given parts
*/
function canBeSeparatedInto(parts, array, peaks) {
var i = 1, result = false;
var blockSize = array.length/parts;
peaks.forEach(function(elem) {
// test to see if there is an element in the array belongs to the ith part
if ((elem+1)/blockSize <= i && (elem+1)/blockSize> i-1) {
i++;
}
});
// set the result to true if there are indeed peaks for every parts
if (i > parts) {
result = true;
}
return result;
}
私のコードの主な問題は、それが性能試験に合格しないということです。私は自分自身をより明確にするためにいくつかの余分なコメントを追加しましたので、
コードスニペットは、長いようです。あなたはそれについて私にいくつかのヒントを教えていただけますか?
なぜあなたがj = 1でチェックを開始し、最後の結果を上がると返すのですか? j = number_of_peaksで始まり、1に向かって作業し、見つかった最初の結果を返します。 – m69
また、canBeSeperatedInto()では、配列全体を反復するのではなく、ピークのないブロックを見つけるとすぐにfalseを返すことができます。 – m69
ピークを見つけている間に、2つのピークの間の最大距離を保存することができます。これは、チェックする必要がある最小ブロックサイズになるためです。 – m69