0ms|1 line Py3 #nlargest #cpp #nth_element 速解 #Leetcode1464 最大的乘積
Python 1行解用heapq.nlargest。C++2行解用nth_element,都是linear 0ms
[C++, Py3 codes請進]
[codes on Leetcode]https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/solutions/8422586/branchless-loopbeats-100-by-anwendeng-2puw/
[C++ Py3用nth_element, nsmallest解Leetcode 3010 Divide an Array Into Subarrays With Minimum Cost]https://www.youtube.com/watch?v=fbpZIn_9F0w
[C++nth_element清單]https://www.youtube.com/watch?v=fbpZIn_9F0w&list=PLPig1VhBR9zI
#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
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);
}
};
沒有留言:
張貼留言