LeetCode 题解工作台
有序数组中差绝对值之和
给你一个 非递减 有序整数数组 nums 。 请你建立并返回一个整数数组 result ,它跟 nums 长度相同,且 result[i] 等于 nums[i] 与数组中所有其他元素差的绝对值之和。 换句话说, result[i] 等于 sum(|nums[i]-nums[j]|) ,其中 0 且 …
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们先求出数组 所有元素的和,记为 ,用变量 记录当前已经枚举过的元素之和。 接下来枚举 ,那么 $ans[i] = nums[i] \times i - t + s - t - nums[i] \times (n - i)$,然后我们更新 ,即 $t = t + nums[i]$。继续枚举下一个元素,直到枚举完所有元素。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个 非递减 有序整数数组 nums 。
请你建立并返回一个整数数组 result,它跟 nums 长度相同,且result[i] 等于 nums[i] 与数组中所有其他元素差的绝对值之和。
换句话说, result[i] 等于 sum(|nums[i]-nums[j]|) ,其中 0 <= j < nums.length 且 j != i (下标从 0 开始)。
示例 1:
输入:nums = [2,3,5] 输出:[4,3,5] 解释:假设数组下标从 0 开始,那么 result[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。
示例 2:
输入:nums = [1,4,6,8,10] 输出:[24,15,13,15,21]
提示:
2 <= nums.length <= 1051 <= nums[i] <= nums[i + 1] <= 104
解题思路
方法一:求和 + 枚举
我们先求出数组 所有元素的和,记为 ,用变量 记录当前已经枚举过的元素之和。
接下来枚举 ,那么 ,然后我们更新 ,即 。继续枚举下一个元素,直到枚举完所有元素。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]:
ans = []
s, t = sum(nums), 0
for i, x in enumerate(nums):
v = x * i - t + s - t - x * (len(nums) - i)
ans.append(v)
t += x
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for understanding of how absolute differences work in sorted arrays.
- question_mark
Check for familiarity with prefix sums and how they can optimize summation problems.
- question_mark
Evaluate the candidate’s ability to optimize an otherwise brute-force solution.
常见陷阱
外企场景- error
Not leveraging the sorted array property, resulting in unnecessary nested loops.
- error
Incorrect use of prefix sums or failure to update them correctly as the array is traversed.
- error
Failing to optimize the solution for larger arrays, which may lead to time limit exceed errors.
进阶变体
外企场景- arrow_right_alt
Instead of absolute differences, calculate the sum of squared differences between each element and others.
- arrow_right_alt
Consider cases where the array is not sorted, and the time complexity will increase.
- arrow_right_alt
Calculate differences based on a dynamic range of indices rather than all elements in the array.