📌  相关文章
📜  查找大于数组中一半元素的元素

📅  最后修改于: 2021-05-06 21:43:29             🧑  作者: Mango

给定n个元素的数组,任务是查找大于数组中元素一半的元素。对于奇数元素,我们需要打印大于floor(n / 2)个元素的元素,其中n是数组中元素的总数。

例子 :

Input :  arr[] = {1, 6, 3, 4}
Output : 4 6

Input  :  arr[] = {10, 4, 2, 8, 9}
Output :  10 9 8

一个简单的方法是获取一个元素并与所有其他元素进行比较,如果该元素更大,则增加计数,然后检查count是否大于n / 2个元素,然后进行打印。

一种有效的方法是按升序对数组进行排序,然后从排序后的数组中打印最后的ceil(n / 2)个元素。
下面是这种基于排序的方法的实现。

C++
// C++ program to find elements that are larger than
// half of the elements in array
#include 
using namespace std;
 
// Prints elements larger than n/2 element
void findLarger(int arr[], int n)
{
    // Sort the array in ascending order
    sort(arr, arr + n);
 
    // Print last ceil(n/2) elements
    for (int i = n-1; i >= n/2; i--)
        cout << arr[i] << " ";    
}
 
// Driver program
int main()
{
    int arr[] = {1, 3, 6, 1, 0, 9};
    int n = sizeof(arr)/sizeof(arr[0]);
    findLarger(arr, n);
    return 0;
}


Java
// Java program to find elements that are
// larger than half of the elements in array
import java.util.*;
 
class Gfg
{
    // Prints elements larger than n/2 element
    static void findLarger(int arr[], int n)
    {
        // Sort the array in ascending order
        Arrays.sort(arr);
      
        // Print last ceil(n/2) elements
        for (int i = n-1; i >= n/2; i--)
            System.out.print(arr[i] + " "); 
    }
      
    // Driver program
    public static void main(String[] args)
    {
        int arr[] = {1, 3, 6, 1, 0, 9};
        int n = arr.length;
        findLarger(arr, n);
    }   
}
 
// This code is contributed by Raghav Sharma


Python
# Python program to find elements that are larger than
# half of the elements in array
# Prints elements larger than n/2 element
def findLarger(arr,n):
 
    # Sort the array in ascending order
    x = sorted(arr)
 
    # Print last ceil(n/2) elements
    for i in range(n/2,n):
        print(x[i]),
 
# Driver program
arr = [1, 3, 6, 1, 0, 9]
n = len(arr);
findLarger(arr,n)
 
# This code is contributed by Afzal Ansari


C#
// C# program to find elements
// that are larger than half
// of the elements in array
using System;
 
class GFG
{
    // Prints elements larger
    // than n/2 element
    static void findLarger(int []arr,
                           int n)
    {
        // Sort the array
        // in ascending order
        Array.Sort(arr);
     
        // Print last ceil(n/2) elements
        for (int i = n - 1; i >= n / 2; i--)
            Console.Write(arr[i] + " ");
    }
     
    // Driver Code
    public static void Main()
    {
        int []arr = {1, 3, 6, 1, 0, 9};
        int n = arr.Length;
        findLarger(arr, n);
    }
}
 
// This code is contributed
// by nitin mittal.


PHP
= $n / 2; $i--)
        echo $arr[$i] , " ";
}
 
// Driver Code
$arr = array(1, 3, 6, 1, 0, 9);
$n = count($arr);
findLarger($arr, $n);
 
// This code is contributed by anuj_67.
?>


Javascript


输出 :

9 6 3