给定一个由n个整数组成的数组arr []和一个整数S。任务是在数组中找到一个元素K ,使得如果使数组> K中的所有元素都等于K,那么所得数组中所有元素的总和就等于S。如果找不到这样的元素,则打印-1 。
例子:
Input: M = 15, arr[] = {12, 3, 6, 7, 8}
Output: 3
Resultant array = {3, 3, 3, 3, 3}
Sum of the array elements = 15 = S
Input: M = 5, arr[] = {1, 3, 2, 5, 8}
Output: 1
方法:对数组进行排序。考虑K的值等于当前元素,遍历数组,然后检查先前元素的总和+(K *剩余元素数)=S 。如果是,则打印K的值,如果找不到此类元素,则最后打印-1 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the required element
int getElement(int a[], int n, int S)
{
// Sort the array
sort(a, a + n);
int sum = 0;
for (int i = 0; i < n; i++) {
// If current element
// satisfies the condition
if (sum + (a[i] * (n - i)) == S)
return a[i];
sum += a[i];
}
// No element found
return -1;
}
// Driver code
int main()
{
int S = 5;
int a[] = { 1, 3, 2, 5, 8 };
int n = sizeof(a) / sizeof(a[0]);
cout << getElement(a, n, S);
return 0;
}
Java
//Java implementation of the approach
import java.util.Arrays;
class GFG
{
// Function to return the required element
static int getElement(int a[], int n, int S)
{
// Sort the array
Arrays.sort(a);
int sum = 0;
for (int i = 0; i < n; i++)
{
// If current element
// satisfies the condition
if (sum + (a[i] * (n - i)) == S)
return a[i];
sum += a[i];
}
// No element found
return -1;
}
// Driver code
public static void main(String[] args)
{
int S = 5;
int a[] = { 1, 3, 2, 5, 8 };
int n = a.length;
System.out.println(getElement(a, n, S));
}
}
// This code is contributed by Mukul singh.
Python 3
# Python3 implementation of the approach
# Function to return the required element
def getElement(a, n, S) :
# Sort the array
a.sort();
sum = 0;
for i in range(n) :
# If current element
# satisfies the condition
if (sum + (a[i] * (n - i)) == S) :
return a[i];
sum += a[i];
# No element found
return -1;
# Driver Code
if __name__ == "__main__" :
S = 5;
a = [ 1, 3, 2, 5, 8 ];
n = len(a) ;
print(getElement(a, n, S)) ;
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the required element
static int getElement(int[] a, int n, int S)
{
// Sort the array
Array.Sort(a);
int sum = 0;
for (int i = 0; i < n; i++)
{
// If current element
// satisfies the condition
if (sum + (a[i] * (n - i)) == S)
return a[i];
sum += a[i];
}
// No element found
return -1;
}
// Driver code
public static void Main()
{
int S = 5;
int[] a = { 1, 3, 2, 5, 8 };
int n = a.Length;
Console.WriteLine(getElement(a, n, S));
}
}
// This code is contributed by Mukul singh.
PHP
输出:
1