题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
中等
相关标签
premium lock icon相关企业
提示

给你一个下标从 0 开始、由 n 个整数组成的数组 arr

arr 中两个元素的 间隔 定义为它们下标之间的 绝对差 。更正式地,arr[i]arr[j] 之间的间隔是 |i - j|

返回一个长度为 n 的数组 intervals ,其中 intervals[i] arr[i] arr 中每个相同元素(与 arr[i] 的值相同)的 间隔之和

注意:|x|x 的绝对值。

 

示例 1:

输入:arr = [2,1,3,1,2,3,3]
输出:[4,2,7,2,4,4,5]
解释:
- 下标 0 :另一个 2 在下标 4 ,|0 - 4| = 4
- 下标 1 :另一个 1 在下标 3 ,|1 - 3| = 2
- 下标 2 :另两个 3 在下标 5 和 6 ,|2 - 5| + |2 - 6| = 7
- 下标 3 :另一个 1 在下标 1 ,|3 - 1| = 2
- 下标 4 :另一个 2 在下标 0 ,|4 - 0| = 4
- 下标 5 :另两个 3 在下标 2 和 6 ,|5 - 2| + |5 - 6| = 4
- 下标 6 :另两个 3 在下标 2 和 5 ,|6 - 2| + |6 - 5| = 5

示例 2:

输入:arr = [10,5,10,10]
输出:[5,0,3,4]
解释:
- 下标 0 :另两个 10 在下标 2 和 3 ,|0 - 2| + |0 - 3| = 5
- 下标 1 :只有这一个 5 在数组中,所以到相同元素的间隔之和是 0
- 下标 2 :另两个 10 在下标 0 和 3 ,|2 - 0| + |2 - 3| = 3
- 下标 3 :另两个 10 在下标 0 和 2 ,|3 - 0| + |3 - 2| = 4

 

提示:

  • n == arr.length
  • 1 <= n <= 105
  • 1 <= arr[i] <= 105
 
通过次数
8,169/20.3K
通过率
40.3%


icon
相关企业

提示 1
For each unique value found in the array, store a sorted list of indices of elements that have this value in the array.

提示 2
One way of doing this is to use a HashMap that maps the values to their list of indices. Update this mapping as you iterate through the array.

提示 3
Process each list of indices separately and get the sum of intervals for the elements of that value by utilizing prefix sums.

提示 4
For each element, keep track of the sum of indices of the identical elements that have come before and that will come after respectively. Use this to calculate the sum of intervals for that element to the rest of the elements with identical values.

相似题目

评论 (0)
💡 讨论区规则

1. 请不要在评论区发表题解!

2. 评论区可以发表关于对翻译的建议、对题目的疑问及其延伸讨论。

3. 如果你需要整理题解思路,获得反馈从而进阶提升,可以去题解区进行。

暂无评论

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
运行和提交代码需要登录
arr =
[2,1,3,1,2,3,3]
Source