/* 自定義代碼塊樣式 */

herrDeng網內搜尋

自訂搜尋

Ads

2026年7月27日 星期一

0ms 速解Leetcode 1464 最大的乘積:別只會用 Sort!試試Py nlargest, C++ nth_element


0ms|1 line Py3 #nlargest #cpp #nth_element 速解 #Leetcode1464 最大的乘積
Python 1行解用heapq.nlargest。C++2行解用nth_element,都是linear 0ms
[C++, Py3 codes請進]

[C++ Py3用nth_element, nsmallest解Leetcode 3010 Divide an Array Into Subarrays With Minimum Cost]https://www.youtube.com/watch?v=fbpZIn_9F0w
  #anwendeng  
------
Video Chapters
00:00 - Problem Analysis: LeetCode 1464
00:30 - Python Implementation: Using heapq.nlargest
01:07 - C++ Implementation: Using std::nth_element
01:52 - Results and 0ms Submission Verification
Py 1-liner
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        return ((x:=heapq.nlargest(2, nums))[0]-1)*(x[1]-1)
C++ 2-line code
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        nth_element(nums.begin(), nums.begin()+1, nums.end(), greater<int>());
        return (nums[0]-1)*(nums[1]-1);
    }
};

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章