0ms C++ Py3 1-line prefix sum速解Leetcode 2574 Left and Right Sum Differences
3 different solutions are given in this video.
標示easy也確實可用簡化的方式來解,如果解答不是線性解,就要加油囉。Key word:Prefix sum
----
The solution marked "easy" can indeed be solved using simplified methods. However, if the solution is not linear, you'll need to work harder. Key word: Prefix sum
[codes on Leetcode]https://leetcode.com/problems/left-and-right-sum-differences/solutions/8316192/compute-running-sumsbeats-100-by-anwende-11jy/
#anwendeng
====
here are the timestamps for the key sections of the walkthrough for LeetCode problem 2574, "Left and Right Sum Differences":
00:00 - Introduction to problem 2574.
00:44 - Explaining the definitions of leftSum and rightSum.
01:43 - Walking through Example 1.
02:49 - Walking through Example 2.
03:01 - Reviewing constraints.
03:14 - C++ solution walkthrough and initial implementation.
05:23 - Optimizing the C++ code (avoiding extra vector allocation).
06:14 - Python solution walkthrough using itertools.accumulate and a one-liner approach.
class Solution:
def leftRightDifference(self, nums: List[int]) -> List[int]:
return (L:=list(accumulate(nums, initial=0))) and [abs(L[-1]-x-2*l) for l, x in zip(L, nums)]
沒有留言:
張貼留言