繁体   English   中英

如何改善 Leetcode 中超出的时间限制?

[英]How to improve time limit exceeded in Leetcode?

我做了练习11。在 Leetcode 中装了更多水的容器,我得到了一个 55/60 的测试用例通过,状态为time limit exceeded ,没有特定的错误。

那么,您对如何修复我的代码以获得 5 个缺失点有任何想法吗?

我的代码是下一个:

 /** * @param {number[]} height * @return {number} */ //to get the area between two endpoints const getArea = (left, right, distance) => { if (left <= right) { return left * distance; } else { return right * distance; } } //this function receive height array to check all areas and find max area const maxArea = (height) => { let left = 0; let right = height.length - 1; let distance = right - left; let maxArea = 0; let area = 0; // for the conditional of the loop, i use the Gauss sum // to get all possible areas. // Example: in the array [2,4,5,10], the possible areas are: // [2,4], [2,5], [2,10], [4,5], [4,10], [5,10] // using the Gauss sum: n(n+1)/2, where n = array.length-1, // i can get the possible areas, in this case, the result is 6 for (let i = 0; i < ((height.length - 1) * ((height.length - 1) + 1) / 2); ++i) { area = getArea(height[left], height[right], distance); if (area > maxArea) { maxArea = area; } //Increase and reduce the pointers to pass to the next possible area if (right == left + 1) { left++; right = height.length - 1; distance = right - left; } else { right -= 1; distance--; } } return maxArea; }; let height = [1, 8, 6, 2, 5, 4, 8, 3, 7]; console.log(maxArea(height));

我在等待答案,我正在学习 Javascript,先谢谢你。

也许尝试更换:

area = getArea(height[left], height[right], distance);

和:

area = height[left] <= height[right] ? left*distance : right*distance;

并一起删除 getArea() function。

这是您的代码的基本简化版本。 最重要的修复是只从数组的边缘向内进行迭代,而不是像你拥有的那样达到 n^2 限制......

 var maxArea = function(height) { let left=0; let right=height.length-1; let maxArea = 0; while (right>left) { // area is the smallest height times distance let area = Math.min(height[left], height[right]) * (right-left) if (area > maxArea) maxArea = area; // move the pointer off the smaller element if (height[left] < height[right]) left++; else right--; } return maxArea }; console.log(maxArea([1,8,6,2,5,4,8,3,7]))

我没有在 leet 代码上尝试过,但如果有比 O(n) 更好的解决方案,我会感到惊讶,而且我没有看到这个想法有任何浪费的常数时间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM