2615. Sum of Distances Medium
1/**
2 * [2615] Sum of Distances
3 *
4 * You are given a 0-indexed integer array nums. There exists an array arr of length nums.length, where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there is no such j, set arr[i] to be 0.
5 * Return the array arr.
6 *
7 * <strong class="example">Example 1:
8 *
9 * Input: nums = [1,3,1,1,2]
10 * Output: [5,0,3,4,0]
11 * Explanation:
12 * When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5.
13 * When i = 1, arr[1] = 0 because there is no other index with value 3.
14 * When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3.
15 * When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4.
16 * When i = 4, arr[4] = 0 because there is no other index with value 2.
17 *
18 * <strong class="example">Example 2:
19 *
20 * Input: nums = [0,5,3]
21 * Output: [0,0,0]
22 * Explanation: Since each element in nums is distinct, arr[i] = 0 for all i.
23 *
24 *
25 * Constraints:
26 *
27 * 1 <= nums.length <= 10^5
28 * 0 <= nums[i] <= 10^9
29 *
30 *
31 * Note: This question is the same as <a href="https://leetcode.com/problems/intervals-between-identical-elements/description/" target="_blank"> 2121: Intervals Between Identical Elements.</a>
32 *
33 */
34pub struct Solution {}
35
36// problem: https://leetcode.com/problems/sum-of-distances/
37// discuss: https://leetcode.com/problems/sum-of-distances/discuss/?currentPage=1&orderBy=most_votes&query=
38
39// submission codes start here
40
41impl Solution {
42 pub fn distance(nums: Vec<i32>) -> Vec<i64> {
43
44 }
45}
46
47// submission codes end
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn test_2615() {
55 }
56}
57
Back
© 2025 bowen.ge All Rights Reserved.