📌  相关文章
📜  使用该元素与所有其他元素的绝对差之和形成的数组

📅  最后修改于: 2021-09-06 06:22:14             🧑  作者: Mango

给定一个由N 个不同正整数组成的排序数组arr[] 。任务是生成一个数组,使得新数组中每个索引处的元素是对应元素与给定数组的所有其他元素的绝对差之和。

朴素的方法:想法是为数组arr[]中的每个元素生成所有可能的对,并为新数组中的每个元素添加对的绝对差的总和。在上述步骤之后为所有元素打印数组。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to return the new array
vector calculate(int* arr, int n)
{
     
    // Initialize the Arraylist
    vector ans;
 
    // Sum of absolute differences
    // of element with all elements
    for(int i = 0; i < n; i++)
    {
         
        // Initialize int sum to 0
        int sum = 0;
 
        for(int j = 0; j < n; j++)
        {
            sum += abs(arr[i] - arr[j]);
        }
 
        // Add the value of sum to ans
        ans.push_back(sum);
    }
 
    // Return the final ans
    return ans;
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 2, 3, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function call
    vector ans = calculate(arr, n);
     
    cout << "[";
    for(auto itr : ans)
        cout << itr << ", ";
         
    cout << "]";
     
    return 0;
}
// This code is contributed by jrishabh99


Java
// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to return the new array
    private static List
    calculate(int[] arr)
    {
        // Length of the arraylist
        int n = arr.length;
 
        // Initialize the Arraylist
        List ans
            = new ArrayList();
 
        // Sum of absolute differences
        // of element with all elements
        for (int i = 0;
            i < arr.length; i++) {
 
            // Initialize int sum to 0
            int sum = 0;
 
            for (int j = 0;
                j < arr.length; j++) {
 
                sum += Math.abs(arr[i] - arr[j]);
            }
 
            // Add the value of sum to ans
            ans.add(sum);
        }
 
        // Return the final ans
        return ans;
    }
 
    // Driver Code
    public static void
        main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 2, 3, 5, 6 };
 
        // Function Call
        System.out.println(calculate(arr));
    }
}


Python3
# Python3 program for the above approach
 
# Function to return the new array
# private static List
def calculate(arr):
 
    # Length of the arraylist
    n = len(arr)
 
    # Initialize the Arraylist
    ans = []
 
    # Sum of absolute differences
    # of element with all elements
    for i in range(n):
 
        # Initialize sum to 0
        sum = 0
 
        for j in range(len(arr)):
            sum += abs(arr[i] - arr[j])
 
        # Add the value of sum to ans
        ans.append(sum)
 
    # Return the final ans
    return ans
 
# Driver Code
if __name__ == '__main__':
 
    # Given array arr[]
    arr = [ 2, 3, 5, 6 ]
 
    # Function call
    print(calculate(arr))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the new array
private static List calculate(int[] arr)
{
     
    // Length of the arraylist
    int n = arr.Length;
 
    // Initialize the Arraylist
    List ans = new List();
 
    // Sum of absolute differences
    // of element with all elements
    for(int i = 0; i < arr.Length; i++)
    {
         
        // Initialize int sum to 0
        int sum = 0;
 
        for(int j = 0; j < arr.Length; j++)
        {
            sum += Math.Abs(arr[i] - arr[j]);
        }
 
        // Add the value of sum to ans
        ans.Add(sum);
    }
 
    // Return the final ans
    return ans;
}
 
// Driver Code
public static void Main(string[] args)
{
     
    // Given array arr[]
    int[] arr = { 2, 3, 5, 6 };
 
    List tmp = calculate(arr);
    Console.Write("[");
    for(int i = 0; i < tmp.Count; i++)
    {
        if(i != tmp.Count - 1)
        {
            Console.Write(tmp[i] + ", ");
        }
        else
        {
            Console.Write(tmp[i]);
        }
    }
    Console.Write("]");
}
}
 
// This code is contributed by rutvik_56


Javascript


C++
// C++ program for the
// above approach
#include 
using namespace std;
 
// Function to return list of
// total Distance of each element
// from other elements in array
vector calculate(int arr[],
                      int n)
{
  int sub = 0;
  int sum = 0;
 
  // Initialize the arraylist
  vector ans;
 
  // Keep track of the
  // accumulated of the
  // sum of values to right
  for (int i = n - 1;
           i >= 0; i--)
    sum += arr[i];
 
  // Keep track of the
  // accumulated subtraction
  // of the values to the left
  for (int i = 0; i < n; i++)
  {
    sum -= arr[i];
 
    // Add the value to the
    // resultant array ans[]
    ans.push_back(sub + (i * arr[i]) -
                 ((n - i - 1) *
                   arr[i]) + sum);
 
    sub -= arr[i];
  }
   
  // Return the final
  // answer
  return ans;
}
 
// Driver Code
int main()
{
  // Initialize the array
  int arr[] = {2, 3, 5, 6};
  int n = sizeof(arr) /
          sizeof(arr[0]);
  vector ans = (calculate(arr, n));
   
  for (int i = 0; i < n; i++)
    cout << ans[i] << " ";
}
 
// This code is contributed by Chitranayal


Java
// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to return list of
    // total Distance of each element
    // from other elements in array
    private static List
    calculate(int[] arr)
    {
        // Length of the array
        int n = arr.length;
        int sub = 0;
        int sum = 0;
 
        // Initialize the arraylist
        List ans
            = new ArrayList();
 
        // Keep track of the accumulated
        // of the sum of values to right
        for (int i = n - 1; i >= 0; i--)
            sum += arr[i];
 
        // Keep track of the accumulated
        // subtraction of the values to the left
        for (int i = 0; i < arr.length; i++) {
 
            sum -= arr[i];
 
            // Add the value to the resultant
            // array ans[]
            ans.add(sub
                    + (i * arr[i])
                    - ((n - i - 1)
                    * arr[i])
                    + sum);
 
            sub -= arr[i];
        }
        // return the final answer
        return ans;
    }
 
    // Driver Code
    public static void
        main(String[] args)
    {
        // Initialize the array
        int[] arr = { 2, 3, 5, 6 };
 
        // Function Call
        System.out.println(calculate(arr));
    }
}


Python3
# Python3 program for the above approach
 
# Function to return list of
# total Distance of each element
# from other elements in array
def calculate (arr):
 
    # Length of the array
    n = len(arr)
    sub = 0
    Sum = 0
 
    # Initialize the ArrayList
    ans = []
 
    # Keep track of the accumulated
    # of the sum of values to right
    for i in range(n - 1, -1, -1):
        Sum += arr[i]
 
    # Keep track of the accumulated
    # subtraction of values to left
    for i in range(len(arr)):
        Sum -= arr[i]
 
        # Add the value to the resultant
        # array ans[]
        ans.append(sub + (i * arr[i]) -
               ((n - i - 1) * arr[i]) + Sum)
 
        sub -= arr[i]
 
    # Return the final answer
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    # Initialize the array
    arr = [ 2, 3, 5, 6 ]
 
    # Function call
    print(calculate(arr))
 
# This code is contributed by himanshu77


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return list of
// total Distance of each element
// from other elements in array
private static List calculate(int[] arr)
{
     
    // Length of the array
    int n = arr.Length;
    int sub = 0;
    int sum = 0;
 
    // Initialize the arraylist
    List ans = new List();
 
    // Keep track of the accumulated
    // of the sum of values to right
    for(int i = n - 1; i >= 0; i--)
        sum += arr[i];
 
    // Keep track of the accumulated
    // subtraction of the values to the left
    for(int i = 0; i < arr.Length; i++)
    {
        sum -= arr[i];
 
        // Add the value to the resultant
        // array ans[]
        ans.Add(sub + (i * arr[i]) -
                 ((n - i - 1) *
                 arr[i]) + sum);
 
        sub -= arr[i];
    }
     
    // return the readonly answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Initialize the array
    int[] arr = { 2, 3, 5, 6 };
 
    // Function Call
    Console.Write("[ ");
    foreach(int i in calculate(arr))
        Console.Write(i + ", ");
         
    Console.Write("]");
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
[8, 6, 6, 8]

时间复杂度: O(N^2)
辅助空间: O(N)

有效的方法:为了优化上述方法,其思想是跟踪左侧值的累积减法和右侧值的总和。每个元素的所有对的差值总和由下式给出:

  • 找到给定数组中所有元素的总和(比如sum )。
  • sub初始化为 0。
  • 遍历给定数组并对每个元素执行以下操作:
    • 从总和中减去当前值arr[i]
    • 使用公式将每个元素的所有对的差值添加到结果数组中:
sub + (i * arr[i]) - ((n - i - 1) * arr[i]) + sum
  • 从总和中减去当前值arr[i]
  • 在上述步骤后打印结果数组。

下面是上述方法的实现:

C++

// C++ program for the
// above approach
#include 
using namespace std;
 
// Function to return list of
// total Distance of each element
// from other elements in array
vector calculate(int arr[],
                      int n)
{
  int sub = 0;
  int sum = 0;
 
  // Initialize the arraylist
  vector ans;
 
  // Keep track of the
  // accumulated of the
  // sum of values to right
  for (int i = n - 1;
           i >= 0; i--)
    sum += arr[i];
 
  // Keep track of the
  // accumulated subtraction
  // of the values to the left
  for (int i = 0; i < n; i++)
  {
    sum -= arr[i];
 
    // Add the value to the
    // resultant array ans[]
    ans.push_back(sub + (i * arr[i]) -
                 ((n - i - 1) *
                   arr[i]) + sum);
 
    sub -= arr[i];
  }
   
  // Return the final
  // answer
  return ans;
}
 
// Driver Code
int main()
{
  // Initialize the array
  int arr[] = {2, 3, 5, 6};
  int n = sizeof(arr) /
          sizeof(arr[0]);
  vector ans = (calculate(arr, n));
   
  for (int i = 0; i < n; i++)
    cout << ans[i] << " ";
}
 
// This code is contributed by Chitranayal

Java

// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to return list of
    // total Distance of each element
    // from other elements in array
    private static List
    calculate(int[] arr)
    {
        // Length of the array
        int n = arr.length;
        int sub = 0;
        int sum = 0;
 
        // Initialize the arraylist
        List ans
            = new ArrayList();
 
        // Keep track of the accumulated
        // of the sum of values to right
        for (int i = n - 1; i >= 0; i--)
            sum += arr[i];
 
        // Keep track of the accumulated
        // subtraction of the values to the left
        for (int i = 0; i < arr.length; i++) {
 
            sum -= arr[i];
 
            // Add the value to the resultant
            // array ans[]
            ans.add(sub
                    + (i * arr[i])
                    - ((n - i - 1)
                    * arr[i])
                    + sum);
 
            sub -= arr[i];
        }
        // return the final answer
        return ans;
    }
 
    // Driver Code
    public static void
        main(String[] args)
    {
        // Initialize the array
        int[] arr = { 2, 3, 5, 6 };
 
        // Function Call
        System.out.println(calculate(arr));
    }
}

蟒蛇3

# Python3 program for the above approach
 
# Function to return list of
# total Distance of each element
# from other elements in array
def calculate (arr):
 
    # Length of the array
    n = len(arr)
    sub = 0
    Sum = 0
 
    # Initialize the ArrayList
    ans = []
 
    # Keep track of the accumulated
    # of the sum of values to right
    for i in range(n - 1, -1, -1):
        Sum += arr[i]
 
    # Keep track of the accumulated
    # subtraction of values to left
    for i in range(len(arr)):
        Sum -= arr[i]
 
        # Add the value to the resultant
        # array ans[]
        ans.append(sub + (i * arr[i]) -
               ((n - i - 1) * arr[i]) + Sum)
 
        sub -= arr[i]
 
    # Return the final answer
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    # Initialize the array
    arr = [ 2, 3, 5, 6 ]
 
    # Function call
    print(calculate(arr))
 
# This code is contributed by himanshu77

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return list of
// total Distance of each element
// from other elements in array
private static List calculate(int[] arr)
{
     
    // Length of the array
    int n = arr.Length;
    int sub = 0;
    int sum = 0;
 
    // Initialize the arraylist
    List ans = new List();
 
    // Keep track of the accumulated
    // of the sum of values to right
    for(int i = n - 1; i >= 0; i--)
        sum += arr[i];
 
    // Keep track of the accumulated
    // subtraction of the values to the left
    for(int i = 0; i < arr.Length; i++)
    {
        sum -= arr[i];
 
        // Add the value to the resultant
        // array ans[]
        ans.Add(sub + (i * arr[i]) -
                 ((n - i - 1) *
                 arr[i]) + sum);
 
        sub -= arr[i];
    }
     
    // return the readonly answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Initialize the array
    int[] arr = { 2, 3, 5, 6 };
 
    // Function Call
    Console.Write("[ ");
    foreach(int i in calculate(arr))
        Console.Write(i + ", ");
         
    Console.Write("]");
}
}
 
// This code is contributed by amal kumar choubey

Javascript


输出:
[8, 6, 6, 8]

时间复杂度: O(N)
空间复杂度: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live