我陷入了下面的編碼問題。Map.prototype.entries() 中似乎存在一個錯誤,但是我希望您對此有專家意見
問題含義:最多包含兩個不同整數的最長子陣列的長度是多少?
這是問題陳述,這是一個 LC 問題
您正在參觀一個農場,該農場從左到右排列著一排果樹。這些樹由一個整數陣列fruits 表示,其中fruits[i] 是第i 棵樹產生的水果型別。
你想收集盡可能多的水果。但是,所有者有一些您必須遵守的嚴格規則:
你只有兩個籃子,每個籃子只能裝一種水果。每個籃子可以容納的水果數量沒有限制。從您選擇的任何一棵樹開始,您必須在向右移動的同時從每棵樹(包括起始樹)中選擇一個果實。采摘的水果必須適合您的其中一個籃子。一旦您到達一棵樹上的水果無法放入您的籃子,您必須停下來。給定整數陣列水果,回傳您可以選擇的最大水果數量。
下面是我的代碼
var totalFruit = function(fruits) {
// create a map of fruit type
var fruitTypes = new Map();
var fruitCount = 0;
var maxFruits = 0;
// iterate till end
for(var indx=0; indx<fruits.length; indx )
{
console.log('\nI am at index:' indx ' now and value is:' fruits[indx]);
// add only 2 types of fruit
if(fruitTypes.size <=2)
{
fruitTypes.set(fruits[indx], fruitCount);
maxFruits = fruitCount;
console.log('\n maxFruit count is ' maxFruits);
}
// if the type of fruit is more than two
if(fruitTypes.size > 2)
{
const iterator1 = fruitTypes.entries();
console.log(iterator1.next().value);
// expected output: ["0", "foo"]
// now remove the first set of fruit
console.log('\nfruittype size is: ' fruitTypes.size ' and fruit count is: ' fruitCount);
const key = fruitTypes.keys();
var keyToDelete = key.next().value;
const value = fruitTypes.values();
var valueToSubtract = value.next().value;
console.log('Deleting fruit type: ' keyToDelete ' and substracting number of fruits=' valueToSubtract);
fruitTypes.delete(keyToDelete);
fruitCount = fruitCount - valueToSubtract;
console.log('\nfruittype size now is: ' fruitTypes.size ' and fruit count is: ' fruitCount);
}
}
console.log("\nmaxFruits=" maxFruits ", fruitcount=" fruitCount);
return Math.max(maxFruits, fruitCount);
};
var fruits = [3,3,3,1,2,1,1,2,3,3,4];
console.log('\nmaximum fruit count=' totalFruit(fruits));
代碼作業正常,但對于給定的測驗用例失敗,即
輸入:[3,3,3,1,2,1,1,2,3,3,4] 輸出:4 預期:5
有人可以幫助解決我犯錯的地方嗎?
uj5u.com熱心網友回復:
這并不是用 1 行代碼或任何東西撰寫的所有花哨的東西,但它運行良好。您可以事件指定更多籃子:
var totalFruit = function(fruits) {
// create a map of fruit type
const nBASKETS = 2;
let nTotalFruit = 0;
let cur_fruit = 0;
let nCurLongest = 0;
let nCurFruitCnt = 0;
let nBeginIdx = 0;
for(let i = 0; i < nBASKETS; i )
// find longest sub-array, record its size, then remove it
for(var indx=0; indx<fruits.length; indx ){
if(indx)
if(fruits[indx] == cur_fruit)
nCurFruitCnt
else {
if(nCurFruitCnt > nCurLongest){
nCurLongest = nCurFruitCnt;
nBeginIdx = indx - nCurFruitCnt
}
nCurFruitCnt = 1;
cur_fruit = fruits[indx]
}
else{ // left boundary
cur_fruit = fruits[indx];
nCurFruitCnt = 1;
nCurLongest = 1;
nBeginIdx = 0
}
if(indx == fruits.length - 1){ // right boundary
if(nCurFruitCnt > nCurLongest){
nCurLongest = nCurFruitCnt;
nBeginIdx = indx - nCurFruitCnt
}
// processed array... remove longest sub-array
nTotalFruit = nCurLongest;
fruits.splice(nBeginIdx, nCurLongest)
}
}
return nTotalFruit
}
var fruits = [3,3,3,3,3,1,1,2,1,1,3,3,3,3];
console.log('\nmaximum fruit count = ' totalFruit(fruits));
uj5u.com熱心網友回復:
- 您需要跟蹤
maxFruitswhile 迭代 - 不要無條件地用 覆寫它maxFruits = fruitCount,而是呼叫maxFruits = Math.max(fruitCount, maxFruits);. 否則,可能會丟失可能更高的先前記錄。 - 使用
fruitTypes.set(fruits[indx], fruitCount);,您沒有添加正確的值 - 您應該添加到Map中該索引處的當前值。例如,給定[1, 2, 2],在第三次迭代后,您希望 Map 包含
1 => 1,
2 => 2
并不是
1 => 1
2 => 3
因為有兩個型別 2 的元素,而不是三個。
但是我不認為這種方法是正確的方法,因為在遇到新時間時確定要減去多少項會有點難看。例如,與
[1, 2, 1, 1, 3]
在迭代 3 時,您需要能夠確定您需要洗掉 1(索引 0)和 2(索引 1) - 總和為 2,同時保留其余部分。Map 中最早的鍵不一定是要洗掉的鍵,正如您在上面的示例中看到的那樣。
這就是我的做法 - 跟蹤直到當前迭代的單個連續型別的數量(例如[3, 3, 3]-> 大小 3)以及直到當前迭代的兩個連續型別的數量(例如[4, 3, 3, 3]-> 大小4)。當找到不同的型別時,將單個連續分配給兩個連續,并取所有迭代中找到的兩個連續的最大值。
const calculateFruits = (fruitTypes) => [...fruitTypes.values()].reduce((a, b) => a b);
var totalFruit = function(fruits) {
let consecutiveIdentical = 0;
let consecutiveOfTwoTypes = 0;
let currentType;
let currentTypes = [];
let maxFruitsSoFar = 0;
for (const type of fruits) {
if (!currentTypes.includes(type)) {
consecutiveOfTwoTypes = consecutiveIdentical;
if (currentTypes.length === 2) {
currentTypes = [currentType, type];
consecutiveOfTwoTypes = consecutiveIdentical;
} else {
currentTypes.push(type);
}
}
consecutiveOfTwoTypes ;
if (currentType !== type) {
consecutiveIdentical = 1;
} else {
consecutiveIdentical ;
}
currentType = type;
maxFruitsSoFar = Math.max(maxFruitsSoFar, consecutiveOfTwoTypes);
}
return maxFruitsSoFar;
}
var fruits = [33, 3, 3, 2, 1, 1, 2, 3, 3, 3, 3]
console.log('maximum fruit count=' totalFruit(fruits));
uj5u.com熱心網友回復:
首先,我復制了水果型別,
然后對于不同的水果,我連續檢查鏈接資料
const calculate = (fruits) => {
const typeOfFruits = [...(new Set(fruits))];
let total = 0;
typeOfFruits.forEach(f => {
let NumberOfFruit = 0;
let chain = false;
for (let i = 0; i < fruits.length; i ) {
if (!(!!NumberOfFruit)) {
if (fruits[i] === f && fruits[i 1] === f) {
NumberOfFruit = 1;
chain = true;
}
}
else {
if (chain) {
if (fruits[i] === f) NumberOfFruit = 1;
else chain = false;
}
}
}
total = NumberOfFruit;
});
return total;
}
calculate([3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4]); // 5
uj5u.com熱心網友回復:
var totalFruit = function(fruits) {
if(fruits.length <=2)
{
console.log("no point going forward, since the length is " fruits.length);
return fruits.length;
} else {
// create a map of fruit type
var fruitTypes = new Map();
var maxFruits = 0;
var prevKey = 0;
var lastTwoConsequtiveValues = 0;
// iterate till end
for(var indx=0; indx<fruits.length; indx )
{
//console.log('\nI am at index:' indx ' now and value is:' fruits[indx]);
// add only 2 types of fruit
if(fruitTypes.size <=2)
{
var keyFruit = fruits[indx];
fruitTypes.set(keyFruit, fruitTypes.get(keyFruit) == undefined ? 1 : fruitTypes.get(keyFruit) 1)
//if(fruitTypes.size >= 2){
console.log("\n******************");
console.log([...fruitTypes.entries()]);
var values = fruitTypes.values();
var val1 = values.next().value;
if(val1 == undefined)
val1 = 0;
var val2 = values.next().value;
if(val2 == undefined)
val2 = 0;
// before deleting store the fruit value
console.log('\nval1=' val1 ' val2=' val2);
lastTwoConsequtiveValues = val1 val2;
console.log('\n 1. lastTwoConsequtiveValues =' lastTwoConsequtiveValues);
maxFruits = Math.max(maxFruits, lastTwoConsequtiveValues);
console.log('\n 1. Maximum value is ' maxFruits);
console.log([...fruitTypes.entries()]);
console.log("\n ");
//}
}
// if the type of fruit is more than two
if(fruitTypes.size > 2)
{
console.log('\nfruittype size is: ' fruitTypes.size);
//if(fruitTypes.size >= 2){
var values = fruitTypes.values();
var val1 = values.next().value;
var val2 = values.next().value;
if(val1 == undefined)
val1 = 0;
if(val2 == undefined)
val2 = 0;
// before deleting store the fruit value
console.log('\nval1=' val1 ' val2=' val2);
lastTwoConsequtiveValues = val1 val2;
console.log('\n 2. lastTwoConsequtiveValues =' lastTwoConsequtiveValues);
maxFruits = Math.max(maxFruits, lastTwoConsequtiveValues);
console.log('\n 2. Maximum value is ' maxFruits);
// }
// now delete the first key
var keys = fruitTypes.keys()
keyToDelete = keys.next().value;
console.log('\nDeleting deleteFirstKey fruit type: ' keyToDelete);
fruitTypes.delete(keyToDelete);
console.log([...fruitTypes.entries()]);
}
}
console.log("\nmaxFruits=" maxFruits);
return maxFruits;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315776.html
標籤:javascript 目的 调试 哈希图
