[leetcode] 1685. Sum of Absolute Differences in a Sorted Array

网友投稿 1064 2022-08-23

[leetcode] 1685. Sum of Absolute Differences in a Sorted Array

[leetcode] 1685. Sum of Absolute Differences in a Sorted Array

Description

You are given an integer array nums sorted in non-decreasing order.

Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.

In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).

Example 1:

Input: nums = [2,3,5]Output: [4,3,5]Explanation: Assuming the arrays are 0-indexed, thenresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.

Example 2:

Input: nums = [1,4,6,8,10]Output: [24,15,13,15,21]

Constraints:

2 <= nums.length <= 1051 <= nums[i] <= nums[i + 1] <= 104

分析

题目的意思是:求一个数组每个位置与其他位置绝对值差的和。这道题我暴力破解了一下,果然超时,后面发现需要一些数学推导,利用有序数组的特性:

res[i]=(nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i])res[i]=(nums[i] * i - (nums[0] + nums[1] + ... + nums[i-1])) + ((nums[i+1] + nums[i+2] + ... + nums[n-1]) - nums[i] * (n-i))res[i]=nums[i]*i-sum[0:i-1]+sum[i+1:n-1]-nums[i]*(n-1-i)sum代表求和了,然后用前缀数组就能搞定res[i]=i*nums[i]-(preSums[i]-preSums[0])+(preSums[n]-preSums[i])-nums[i]*(n-i)

代码

class Solution: def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: n=len(nums) preSums=[0]*(n+1) res=[0]*(n) for i in range(1,n+1): preSums[i]=preSums[i-1]+nums[i-1] for i in range(n): res[i]=i*nums[i]-(preSums[i]-preSums[0])+(preSums[n]-preSums[i])-nums[i]*(n-i) return res

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1523. Count Odd Numbers in an Interval Range
下一篇:[leetcode] 543. Diameter of Binary Tree
相关文章

 发表评论

暂时没有评论,来抢沙发吧~