给定N个整数和整数K的数组arr [] ,任务是查找数组中的异常数。异常是一个数字,其与数组中所有其他数字之间的绝对差大于K。查找异常数量。
例子:
Input: arr[] = {1, 3, 5}, k = 1
Output: 2
1 and 3 are the anomalies.
|1 – (3 + 5)| = 7 > 1
|3 – (1 + 5)| = 3 > 1
Input: arr[] = {7, 1, 8}, k = 5
Output: 1
方法:找到所有数组元素的总和,然后将其存储在sum中,现在对于数组arr [i]的每个元素,如果arr [i]与sum – arr [i]的绝对差大于k ,则为异常。计算数组中的所有异常,最后打印结果。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the number of anomalies
static int countAnomalies(int arr[],
int n, int k)
{
// To store the count of anomalies
int cnt = 0;
// To store the sum of the array elements
int i, sum = 0;
// Find the sum of the array elements
for (i = 0; i < n; i++)
sum += arr[i];
// Count the anomalies
for (i = 0; i < n; i++)
if (abs(arr[i] -
(sum - arr[i])) > k)
cnt++;
return cnt;
}
// Driver code
int main()
{
int arr[] = { 1, 3, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 1;
cout << countAnomalies(arr, n, k);
}
// This code is contributed
// by Code_Mech
Java
// Java implementation of the approach
class GFG {
// Function to return the number of anomalies
static int countAnomalies(int arr[], int n, int k)
{
// To store the count of anomalies
int cnt = 0;
// To store the sum of the array elements
int i, sum = 0;
// Find the sum of the array elements
for (i = 0; i < n; i++)
sum += arr[i];
// Count the anomalies
for (i = 0; i < n; i++)
if (Math.abs(arr[i] - (sum - arr[i])) > k)
cnt++;
return cnt;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 3, 5 };
int n = arr.length;
int k = 1;
System.out.print(countAnomalies(arr, n, k));
}
}
Python3
# Python3 implementation of the approach
# Function to return the
# number of anomalies
def countAnomalies(arr, n, k):
# To store the count of anomalies
cnt = 0
# To store the Sum of
# the array elements
i, Sum = 0, 0
# Find the Sum of the array elements
for i in range(n):
Sum += arr[i]
# Count the anomalies
for i in range(n):
if (abs(arr[i] - (Sum - arr[i])) > k):
cnt += 1
return cnt
# Driver code
arr = [1, 3, 5]
n = len(arr)
k = 1
print(countAnomalies(arr, n, k))
# This code is contributed
# by mohit kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the number of anomalies
static int countAnomalies(int[] arr, int n, int k)
{
// To store the count of anomalies
int cnt = 0;
// To store the sum of the array elements
int i, sum = 0;
// Find the sum of the array elements
for (i = 0; i < n; i++)
sum += arr[i];
// Count the anomalies
for (i = 0; i < n; i++)
if (Math.Abs(arr[i] - (sum - arr[i])) > k)
cnt++;
return cnt;
}
// Driver code
public static void Main()
{
int[] arr = { 1, 3, 5 };
int n = arr.Length;
int k = 1;
Console.WriteLine(countAnomalies(arr, n, k));
}
}
// This code is contributed by Code_Mech.
PHP
$k)
$cnt++;
return $cnt;
}
// Driver code
$arr = array(1, 3, 5);
$n = count($arr);
$k = 1;
echo countAnomalies($arr, $n, $k);
// This code is contributed by Ryuga
?>
输出:
2