📌  相关文章
📜  每个数组元素的出现索引的绝对差之和

📅  最后修改于: 2021-05-14 01:54:23             🧑  作者: Mango

给定一个由N个整数组成的数组arr [] ,每个数组元素arr [i]的任务是打印| i – j |的和。对于所有可能的索引j ,使得arr [i] = arr [j]

例子:

简单方法:最简单的方法是遍历给定的阵列和用于每个元素ARR [I](0≤I≤N),遍历数组,并检查是否ARR [i]是相同ARR [J](0≤Ĵ≤ N )。如果发现为真,则将abs(i – j)添加到总和中,然后打印出每个数组元素获得的总和。

时间复杂度: O(N 2 ),其中N是给定数组的大小。
辅助空间: O(N)

高效方法:想法是使用Map数据结构来优化上述方法。请按照以下步骤解决问题:

  1. 初始化Map来存储索引向量,以重复数组中存在的每个唯一元素。
  2. i = 0到N – 1遍历给定的数组,并且对于每个数组元素arr [i] ,将其和初始化为0,并遍历矢量映射[arr [i]] ,该映射存储元素arr [的出现次数的索引我]
  3. 对于向量中存在的每个值j ,将总和增加abs(i – j)
  4. 遍历向量后,将元素的总和存储在索引i并打印总和。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find sum of differences
// of indices of occurrences of each
// unique array element
void sum(int arr[], int n)
{
    // Stores indices of each
    // array element
    map > mp;
 
    // Store the indices
    for (int i = 0; i < n; i++) {
        mp[arr[i]].push_back(i);
    }
 
    // Stores the sums
    int ans[n];
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Find sum for each element
        int sum = 0;
 
        // Iterate over the Map
        for (auto it : mp[arr[i]]) {
 
            // Calculate sum of
            // occurrences of arr[i]
            sum += abs(it - i);
         
        }
 
        // Store sum for
        // current element
        ans[i] = sum;
    }
 
    // Print answer for each element
    for (int i = 0; i < n; i++) {
        cout << ans[i] << " ";
    }
    return;
}
 
// Driver Code
int main()
{
 
    // Given array
    int arr[] = { 1, 3, 1, 1, 2 };
 
    // Given size
    int n = sizeof(arr)
            / sizeof(arr[0]);
 
    // Function call
    sum(arr, n);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find sum of differences
// of indices of occurrences of each
// unique array element
static void sum(int arr[], int n)
{
     
    // Stores indices of each
    // array element
    HashMap> mp = new HashMap<>();
 
    // Store the indices
    for(int i = 0; i < n; i++)
    {
        Vector v = new Vector<>();
        v.add(i);
         
        if (mp.containsKey(arr[i]))
            v.addAll(mp.get(arr[i]));
         
        mp.put(arr[i], v);
    }
 
    // Stores the sums
    int []ans = new int[n];
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // Find sum for each element
        int sum = 0;
         
        // Iterate over the Map
        for(int it : mp.get(arr[i]))
        {
             
            // Calculate sum of
            // occurrences of arr[i]
            sum += Math.abs(it - i);
        }
 
        // Store sum for
        // current element
        ans[i] = sum;
    }
 
    // Print answer for each element
    for(int i = 0; i < n; i++)
    {
        System.out.print(ans[i] + " ");
    }
    return;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array
    int arr[] = { 1, 3, 1, 1, 2 };
 
    // Given size
    int n = arr.length;
 
    // Function call
    sum(arr, n);
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program for the above approach
from collections import defaultdict
 
# Function to find sum of differences
# of indices of occurrences of each
# unique array element
def sum_i(arr, n):
   
    # Stores indices of each
    # array element
    mp = defaultdict(lambda : [])
 
    # Store the indices
    for i in range(n):
        mp[arr[i]].append(i)
 
    # Stores the sums
    ans = [0] * n
 
    # Traverse the array
    for i in range(n):
 
        # Find sum for each element
        sum = 0
 
        # Iterate over the Map
        for it in mp[arr[i]]:
 
            # Calculate sum of
            # occurrences of arr[i]
            sum += abs(it - i)
 
            # Store sum for
            # current element
            ans[i] = sum
 
    # Print answer for each element
    for i in range(n):
        print(ans[i], end = " ")
 
# Driver code
if __name__ == '__main__':
   
    # Given array
    arr = [ 1, 3, 1, 1, 2 ]
 
    # Given size
    n = len(arr)
 
    # Function Call
    sum_i(arr, n)
 
# This code is contributed by Shivam Singh


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find sum of differences
// of indices of occurrences of each
// unique array element
static void sum(int []arr, int n)
{
     
    // Stores indices of each
    // array element
    Dictionary> mp = new Dictionary>();
 
    // Store the indices
    for(int i = 0; i < n; i++)
    {
        List v = new List();
        v.Add(i);
         
        if (mp.ContainsKey(arr[i]))
            v.AddRange(mp[arr[i]]);
         
        mp[arr[i]]= v;
    }
 
    // Stores the sums
    int []ans = new int[n];
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // Find sum for each element
        int sum = 0;
         
        // Iterate over the Map
        foreach(int it in mp[arr[i]])
        {
             
            // Calculate sum of
            // occurrences of arr[i]
            sum += Math.Abs(it - i);
        }
 
        // Store sum for
        // current element
        ans[i] = sum;
    }
 
    // Print answer for each element
    for(int i = 0; i < n; i++)
    {
        Console.Write(ans[i] + " ");
    }
    return;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array
    int []arr = { 1, 3, 1, 1, 2 };
 
    // Given size
    int n = arr.Length;
 
    // Function call
    sum(arr, n);
}
}
 
// This code is contributed by shikhasingrajput


输出:
5 0 3 4 0

时间复杂度: O(N * L)其中N是给定数组的大小, L是任何数组元素的最大频率。
辅助空间: O(N)