基于MaxHeap的maxProductFinderK函数问题排查:仅过4/5测试用例
任务描述
创建maxProductFinderK()函数,接收数字列表与整数k,返回列表中任意k个整数可得到的最大乘积,列表长度≥k。
示例:
maxProductFinderK([-8, 6, -7, 3, 2, 1, -9], 2)应返回72maxProductFinderK([-8, 6, -7, 3, 2, 1, -9], 3)应返回432
问题情况
我实现的代码仅通过4/5测试用例,不清楚问题所在,代码如下:
class MaxHeap { constructor() { this.heap = []; } get size() { return this.heap.length; } getParent(index) { return Math.floor((index - 1) / 2); } getLeft(index) { return 2 * index + 1; } getRight(index) { return 2 * index + 2; } add(value) { this.heap.push(value); this.heapifyUp(); } heapifyUp() { let index = this.heap.length - 1; while (index > 0) { let parentIndex = this.getParent(index); if (this.heap[parentIndex] < this.heap[index]) { [this.heap[parentIndex], this.heap[index]] = [this.heap[index], this.heap[parentIndex]]; index = parentIndex; } else { break; } } } remove() { if (this.heap.length === 0) { return null; } if (this.heap.length === 1) { return this.heap.pop(); } let max = this.heap[0]; this.heap[0] = this.heap.pop(); this.heapifyDown(0); return max; } heapifyDown(index) { let left = this.getLeft(index); let right = this.getRight(index); let largest = index; if (left < this.heap.length && this.heap[left] > this.heap[largest]) { largest = left; } if (right < this.heap.length && this.heap[right] > this.heap[largest]) { largest = right; } if (largest !== index) { [this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]]; this.heapifyDown(largest); } } printHeap() { let arr = []; while (this.heap.length > 0) { let max = this.remove(); arr.push(max); } return arr; } } function maxProductFinderK(numbers, size) { if(numbers.length === 0 || size === 0){ return 0 } if(size === numbers.length){ return numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 1); } let positive = new MaxHeap(); let negative = new MaxHeap(); for (let n of numbers) { if (n < 0) { negative.add(Math.abs(n)); } else { positive.add(n); } } let k = size; positive = positive.printHeap(); negative = negative.printHeap(); console.log(positive); console.log(negative); let result = 1; while (negative.length >= 2 && positive.length >= 2 && k>=2) { let negativeProduct = negative[0] * negative[1] let positiveProduct = positive[0] * positive[1]; if (negativeProduct > positiveProduct) { result *= negativeProduct; negative.shift(); negative.shift(); } else { result *= positiveProduct; positive.shift(); positive.shift(); } k -= 2; } while (positive.length >= 2 && k>=2) { result *= (positive[0] * positive[1]); positive.shift(); positive.shift(); k -= 2; } while (negative.length >= 2 && k>=2) { result *= (negative[0] * negative[1]); negative.shift(); negative.shift(); k -= 2; } // console.log(k) if (k === 1) { if (positive.length > 0) { result *= positive[0]; } else { result *= negative[0]; } } console.log("result is "+ result); return result }
内容的提问来源于stack exchange,提问作者asim elnour
相关产品推荐
相关产品推荐

