给定一个成对和数组和原始数组的大小(n),构造原始数组。
数组的成对和数组是包含有序形式的所有对的和的数组。例如,arr [] = {6,8,3,4}的成对和数组为{14,9,10,11,12,7}。
通常,arr [0..n-1]的成对和数组为{arr [0] + arr [1],arr [0] + arr [2],……。,arr [1] + arr [ 2],arr [1] + arr [3],……。,arr [2] + arr [3],arr [2] + arr [4],…。,arr [n-2] + arr [n -1}。
“给出一个成对和数组,构造原始数组。”
强烈建议您最小化浏览器,然后自己尝试。
假设给定的数组为“ pair []”,并且原始数组中有n个元素。如果我们看几个例子,我们可以看到arr [0]是pair [0] + pair [1] – pair [n-1]的一半。请注意,对[0] +对[1] –对[n-1]的值是(arr [0] + arr [1])+(arr [0] + arr [2])–(arr [1 ] + arr [2])。
一旦我们评估了arr [0],我们就可以通过减去arr [0]来评估其他元素。例如,可以通过从对[0]中减去arr [0]来评估arr [1],可以从对[1]中减去arr [0]来评估arr [2]。
以下是上述想法的实现。
C++
#include
using namespace std;
// Fills element in arr[] from its pair sum array pair[].
// n is size of arr[]
void constructArr(int arr[], int pair[], int n)
{
arr[0] = (pair[0]+pair[1]-pair[n-1]) / 2;
for (int i=1; i
Java
import java.io.*;
class PairSum {
// Fills element in arr[] from its pair sum array pair[].
// n is size of arr[]
static void constructArr(int arr[], int pair[], int n)
{
arr[0] = (pair[0]+pair[1]-pair[n-1]) / 2;
for (int i=1; i
Python3
# Fills element in arr[] from its
# pair sum array pair[].
# n is size of arr[]
def constructArr(arr,pair,n):
arr [0] = (pair[0]+pair[1]-pair[n-1])//2
for i in range(1,n):
arr[i] = pair[i-1]-arr[0]
# Driver code
if __name__=='__main__':
pair = [15, 13, 11, 10, 12, 10, 9, 8, 7, 5]
n =5
arr = [0]*n
constructArr(arr,pair,n)
for i in range(n):
print(arr[i],end =" ")
# This code is contributed by
# Shrikant13
C#
// C# program to construct an
// array from its pair-sum array
using System;
class PairSum
{
// Fills element in arr[] from its
// pair sum array pair[].
// n is size of arr[]
static void constructArr(int []arr, int []pair,
int n)
{
arr[0] = (pair[0] + pair[1] - pair[n - 1]) / 2;
for (int i = 1; i < n; i++)
arr[i] = pair[i - 1] - arr[0];
}
// Driver program to test above function
public static void Main()
{
int []pair = {15, 13, 11, 10, 12,
10, 9, 8, 7, 5};
int n = 5;
int []arr = new int[n];
constructArr(arr, pair, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by nitin mittal
PHP
Javascript
输出:
8 7 5 3 2