📌  相关文章
📜  使得给定数组可以分为满足给定条件的两组的K数

📅  最后修改于: 2021-04-24 20:10:18             🧑  作者: Mango

给定大小为N的数组arr [] 。任务是找到K的数量,以便如果数组中少于K的元素在一组中,而其余元素在另一组中,则可以将数组划分为包含相等数量元素的两组。

注意N始终为偶数。

例子:

方法:一种有效的方法是对数组进行排序。然后,如果两个中间数字相同,则答案为零;否则,答案为两个数字之间的差。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the count of K's
// such that the array can be divided
// into two sets containing equal number
// of elements when all the elements less
// than K are in one set and the rest
// of the elements are in the other set
int two_sets(int a[], int n)
{
    // Sort the given array
    sort(a, a + n);
  
    // Return number of such Ks
    return a[n / 2] - a[(n / 2) - 1];
}
  
// Driver code
int main()
{
    int a[] = { 1, 4, 4, 6, 7, 9 };
    int n = sizeof(a) / sizeof(a[0]);
  
    cout << two_sets(a, n);
  
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
  
class GFG 
{
  
// Function to return the count of K's
// such that the array can be divided
// into two sets containing equal number
// of elements when all the elements less
// than K are in one set and the rest
// of the elements are in the other set
static int two_sets(int a[], int n)
{
    // Sort the given array
    Arrays.sort(a);
  
    // Return number of such Ks
    return a[n / 2] - a[(n / 2) - 1];
}
  
// Driver code
public static void main(String []args)
{
    int a[] = { 1, 4, 4, 6, 7, 9 };
    int n = a.length;
  
    System.out.println(two_sets(a, n));
}
}
  
// This code is contributed by Rajput-Ji


Python3
# Python3 implementation of the approach 
  
# Function to return the count of K's 
# such that the array can be divided 
# into two sets containing equal number 
# of elements when all the elements less 
# than K are in one set and the rest 
# of the elements are in the other set 
def two_sets(a, n) :
  
    # Sort the given array 
    a.sort(); 
  
    # Return number of such Ks 
    return (a[n // 2] - a[(n // 2) - 1]); 
  
# Driver code 
if __name__ == "__main__" : 
  
    a = [ 1, 4, 4, 6, 7, 9 ]; 
    n = len(a); 
  
    print(two_sets(a, n)); 
  
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System; 
  
class GFG 
{
  
// Function to return the count of K's
// such that the array can be divided
// into two sets containing equal number
// of elements when all the elements less
// than K are in one set and the rest
// of the elements are in the other set
static int two_sets(int []a, int n)
{
    // Sort the given array
    Array.Sort(a);
  
    // Return number of such Ks
    return a[n / 2] - a[(n / 2) - 1];
}
  
// Driver code
public static void Main(String []args)
{
    int []a = { 1, 4, 4, 6, 7, 9 };
    int n = a.Length;
  
    Console.WriteLine(two_sets(a, n));
}
}
  
// This code is contributed by PrinciRaj1992


输出:
2