📌  相关文章
📜  打印所有出现超过 N / K 次的数组元素

📅  最后修改于: 2021-10-25 10:34:01             🧑  作者: Mango

给定一个大小为N的数组arr[]和一个整数K ,任务是找到出现次数超过(N / K)次的所有数组元素。

例子:

朴素的方法:解决这个问题的最简单的方法是遍历数组,对于每个不同的数组元素,计算它的频率并检查是否超过N / K。如果发现为真,则打印数组元素。

时间复杂度: O(N 2 )
辅助空间: O(1)

基于排序的方法:思想是对数组进行排序,然后遍历数组,通过检查相邻元素是否相等来计算每个不同数组元素的频率。如果发现数组元素的频率大于N / K ,则打印数组元素。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to print all array elements
// whose frequency is greater than N / K
void NDivKWithFreq(int arr[], int N, int K)
{
    // Sort the array, arr[]
    sort(arr, arr + N);
 
    // Traverse the array
    for (int i = 0; i < N;) {
 
        // Stores frequency of arr[i]
        int cnt = 1;
 
        // Traverse array elements which
        // is equal to arr[i]
        while ((i + 1) < N
               && arr[i] == arr[i + 1]) {
 
            // Update cnt
            cnt++;
 
            // Update i
            i++;
        }
 
        // If frequency of arr[i] is
        // greater than (N / K)
        if (cnt > (N / K)) {
 
            cout << arr[i] << " ";
        }
        i++;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 4;
 
    NDivKWithFreq(arr, N, K);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to print all array elements
// whose frequency is greater than N / K
static void NDivKWithFreq(int arr[], int N, int K)
{
    // Sort the array, arr[]
    Arrays.sort(arr);
 
    // Traverse the array
    for (int i = 0; i < N;) {
 
        // Stores frequency of arr[i]
        int cnt = 1;
 
        // Traverse array elements which
        // is equal to arr[i]
        while ((i + 1) < N
               && arr[i] == arr[i + 1]) {
 
            // Update cnt
            cnt++;
 
            // Update i
            i++;
        }
 
        // If frequency of arr[i] is
        // greater than (N / K)
        if (cnt > (N / K)) {
 
            System.out.print(arr[i]+ " ");
        }
        i++;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
    int N = arr.length;
    int K = 4;
 
    NDivKWithFreq(arr, N, K);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
 
# Function to prall array elements
# whose frequency is greater than N / K
def NDivKWithFreq(arr, N, K):
     
    # Sort the array, arr[]
    arr = sorted(arr)
 
    # Traverse the array
    i = 0
     
    while i < N:
         
        # Stores frequency of arr[i]
        cnt = 1
 
        # Traverse array elements which
        # is equal to arr[i]
        while ((i + 1) < N and
               arr[i] == arr[i + 1]):
 
            # Update cnt
            cnt += 1
 
            # Update i
            i += 1
 
        # If frequency of arr[i] is
        # greater than (N / K)
        if (cnt > (N // K)):
            print(arr[i], end = " ")
             
        i += 1
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 2, 6, 6, 6, 6, 7, 10 ]
    N = len(arr)
    K = 4
 
    NDivKWithFreq(arr, N, K)
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach 
using System;
    
class GFG{
    
// Function to print all array elements
// whose frequency is greater than N / K
static void NDivKWithFreq(int[] arr, int N,
                          int K)
{
     
    // Sort the array, arr[]
    Array.Sort(arr);
  
    // Traverse the array
    for(int i = 0; i < N;)
    {
         
        // Stores frequency of arr[i]
        int cnt = 1;
  
        // Traverse array elements which
        // is equal to arr[i]
        while ((i + 1) < N &&
               arr[i] == arr[i + 1])
        {
             
            // Update cnt
            cnt++;
  
            // Update i
            i++;
        }
  
        // If frequency of arr[i] is
        // greater than (N / K)
        if (cnt > (N / K))
        {
            Console.Write(arr[i] + " ");
        }
        i++;
    }
}
    
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
    int N = arr.Length;
    int K = 4;
  
    NDivKWithFreq(arr, N, K);
}
}
 
// This code is contributed by code_hunt


Javascript


C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to+ find the upper_bound of
// an array element
int upperBound(int arr[], int N, int K)
{
 
    // Stores minimum index
    // in which K lies
    int l = 0;
 
    // Stores maximum index
    // in which K lies
    int r = N;
 
    // Calculate the upper
    // bound of K
    while (l < r) {
 
        // Stores mid element
        // of l and r
        int mid = (l + r) / 2;
 
        // If arr[mid] is less
        // than or equal to K
        if (arr[mid] <= K) {
 
            // Right subarray
            l = mid + 1;
        }
 
        else {
 
            // Left subarray
            r = mid;
        }
    }
    return l;
}
 
// Function to print all array elements
// whose frequency is greater than N / K
void NDivKWithFreq(int arr[], int N, int K)
{
 
    // Sort the array arr[]
    sort(arr, arr + N);
 
    // Stores index of
    // an array element
    int i = 0;
 
    // Traverse the array
    while (i < N) {
 
        // Stores upper bound of arr[i]
        int X = upperBound(arr, N, arr[i]);
 
        // If frequency of arr[i] is
        // greater than N / 4
        if ((X - i) > N / 4) {
 
            cout << arr[i] << " ";
        }
 
        // Update i
        i = X;
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int K = 4;
 
    // Function Call
    NDivKWithFreq(arr, N, K);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to+ find the upper_bound of
// an array element
static int upperBound(int arr[], int N, int K)
{
 
    // Stores minimum index
    // in which K lies
    int l = 0;
 
    // Stores maximum index
    // in which K lies
    int r = N;
 
    // Calculate the upper
    // bound of K
    while (l < r)
    {
 
        // Stores mid element
        // of l and r
        int mid = (l + r) / 2;
 
        // If arr[mid] is less
        // than or equal to K
        if (arr[mid] <= K)
        {
 
            // Right subarray
            l = mid + 1;
        }
 
        else
        {
 
            // Left subarray
            r = mid;
        }
    }
    return l;
}
 
// Function to print all array elements
// whose frequency is greater than N / K
static void NDivKWithFreq(int arr[], int N, int K)
{
 
    // Sort the array arr[]
    Arrays.sort(arr);
 
    // Stores index of
    // an array element
    int i = 0;
 
    // Traverse the array
    while (i < N)
    {
 
        // Stores upper bound of arr[i]
        int X = upperBound(arr, N, arr[i]);
 
        // If frequency of arr[i] is
        // greater than N / 4
        if ((X - i) > N / 4)
        {
 
            System.out.print(arr[i] + " ");
        }
 
        // Update i
        i = X;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
 
    // Size of array
    int N = arr.length;
    int K = 4;
 
    // Function Call
    NDivKWithFreq(arr, N, K);
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python program to implement
# the above approach
 
# Function to+ find the upper_bound of
# an array element
def upperBound(arr, N, K):
 
  # Stores minimum index
    # in which K lies
    l = 0;
 
    # Stores maximum index
    # in which K lies
    r = N;
 
    # Calculate the upper
    # bound of K
    while (l < r):
 
        # Stores mid element
        # of l and r
        mid = (l + r) // 2;
 
        # If arr[mid] is less
        # than or equal to K
        if (arr[mid] <= K):
 
            # Right subarray
            l = mid + 1;
        else:
 
            # Left subarray
            r = mid;
    return l;
 
# Function to prall array elements
# whose frequency is greater than N / K
def NDivKWithFreq(arr, N, K):
   
  # Sort the array arr
    arr.sort();
 
    # Stores index of
    # an array element
    i = 0;
 
    # Traverse the array
    while (i < N):
 
        # Stores upper bound of arr[i]
        X = upperBound(arr, N, arr[i]);
 
        # If frequency of arr[i] is
        # greater than N / 4
        if ((X - i) > N // 4):
            print(arr[i], end="");
 
        # Update i
        i = X;
 
# Driver Code
if __name__ == '__main__':
   
    # Given array arr
    arr = [1, 2, 2, 6, 6, 6, 6, 7, 10];
 
    # Size of array
    N = len(arr);
    K = 4;
 
    # Function Call
    NDivKWithFreq(arr, N, K);
 
    # This code is contributed by 29AjayKumar


C#
// C# program to implement
// the above approach
using System;
class GFG
{
 
  // Function to+ find the upper_bound of
  // an array element
  static int upperBound(int []arr, int N, int K)
  {
 
    // Stores minimum index
    // in which K lies
    int l = 0;
 
    // Stores maximum index
    // in which K lies
    int r = N;
 
    // Calculate the upper
    // bound of K
    while (l < r)
    {
 
      // Stores mid element
      // of l and r
      int mid = (l + r) / 2;
 
      // If arr[mid] is less
      // than or equal to K
      if (arr[mid] <= K)
      {
 
        // Right subarray
        l = mid + 1;
      }
 
      else
      {
 
        // Left subarray
        r = mid;
      }
    }
    return l;
  }
 
  // Function to print all array elements
  // whose frequency is greater than N / K
  static void NDivKWithFreq(int []arr, int N, int K)
  {
 
    // Sort the array arr[]
    Array.Sort(arr);
 
    // Stores index of
    // an array element
    int i = 0;
 
    // Traverse the array
    while (i < N)
    {
 
      // Stores upper bound of arr[i]
      int X = upperBound(arr, N, arr[i]);
 
      // If frequency of arr[i] is
      // greater than N / 4
      if ((X - i) > N / 4)
      {
 
        Console.Write(arr[i] + " ");
      }
 
      // Update i
      i = X;
    }
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Given array arr[]
    int []arr = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
 
    // Size of array
    int N = arr.Length;
    int K = 4;
 
    // Function Call
    NDivKWithFreq(arr, N, K);
  }
}
 
// This code is contributed by AnkThon


Javascript


Python3
# Python3 implementation
from collections import Counter
 
# Function to find the number of array
# elements with frequency more than n/k times
def printElements(arr, n, k):
 
    # Calculating n/k
    x = n//k
 
    # Counting frequency of every
    # element using Counter
    mp = Counter(arr)
     
    # Traverse the map and print all
    # the elements with occurrence atleast n/k times
    for it in mp:
        if mp[it] > x:
            print(it)
 
 
# Driver code
arr = [1, 2, 2, 6, 6, 6, 6, 7, 10]
 
# Size of array
n = len(arr)
k = 4
 
printElements(arr, n, k)
 
# This code is contributed by vikkycirus


输出:
6

时间复杂度: O(N * log 2 N)
辅助空间: O(1)

基于二分搜索的方法:该问题可以使用二分搜索技术解决。其思想是遍历数组,通过计算数组元素的上界来计算每个不同数组元素的频率。最后,检查数组元素的频率是否大于N/K 。如果发现为真,则打印数组元素。请按照以下步骤解决问题:

  • 对数组进行排序, arr[]
  • 使用变量i遍历数组并找到arr[i]的上限,例如X并检查(x – i)是否大于N / K。如果发现为真,则打印arr[i]
  • 最后,更新i = X

C++

// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to+ find the upper_bound of
// an array element
int upperBound(int arr[], int N, int K)
{
 
    // Stores minimum index
    // in which K lies
    int l = 0;
 
    // Stores maximum index
    // in which K lies
    int r = N;
 
    // Calculate the upper
    // bound of K
    while (l < r) {
 
        // Stores mid element
        // of l and r
        int mid = (l + r) / 2;
 
        // If arr[mid] is less
        // than or equal to K
        if (arr[mid] <= K) {
 
            // Right subarray
            l = mid + 1;
        }
 
        else {
 
            // Left subarray
            r = mid;
        }
    }
    return l;
}
 
// Function to print all array elements
// whose frequency is greater than N / K
void NDivKWithFreq(int arr[], int N, int K)
{
 
    // Sort the array arr[]
    sort(arr, arr + N);
 
    // Stores index of
    // an array element
    int i = 0;
 
    // Traverse the array
    while (i < N) {
 
        // Stores upper bound of arr[i]
        int X = upperBound(arr, N, arr[i]);
 
        // If frequency of arr[i] is
        // greater than N / 4
        if ((X - i) > N / 4) {
 
            cout << arr[i] << " ";
        }
 
        // Update i
        i = X;
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int K = 4;
 
    // Function Call
    NDivKWithFreq(arr, N, K);
 
    return 0;
}

Java

// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to+ find the upper_bound of
// an array element
static int upperBound(int arr[], int N, int K)
{
 
    // Stores minimum index
    // in which K lies
    int l = 0;
 
    // Stores maximum index
    // in which K lies
    int r = N;
 
    // Calculate the upper
    // bound of K
    while (l < r)
    {
 
        // Stores mid element
        // of l and r
        int mid = (l + r) / 2;
 
        // If arr[mid] is less
        // than or equal to K
        if (arr[mid] <= K)
        {
 
            // Right subarray
            l = mid + 1;
        }
 
        else
        {
 
            // Left subarray
            r = mid;
        }
    }
    return l;
}
 
// Function to print all array elements
// whose frequency is greater than N / K
static void NDivKWithFreq(int arr[], int N, int K)
{
 
    // Sort the array arr[]
    Arrays.sort(arr);
 
    // Stores index of
    // an array element
    int i = 0;
 
    // Traverse the array
    while (i < N)
    {
 
        // Stores upper bound of arr[i]
        int X = upperBound(arr, N, arr[i]);
 
        // If frequency of arr[i] is
        // greater than N / 4
        if ((X - i) > N / 4)
        {
 
            System.out.print(arr[i] + " ");
        }
 
        // Update i
        i = X;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
 
    // Size of array
    int N = arr.length;
    int K = 4;
 
    // Function Call
    NDivKWithFreq(arr, N, K);
}
}
 
// This code is contributed by shikhasingrajput

蟒蛇3

# Python program to implement
# the above approach
 
# Function to+ find the upper_bound of
# an array element
def upperBound(arr, N, K):
 
  # Stores minimum index
    # in which K lies
    l = 0;
 
    # Stores maximum index
    # in which K lies
    r = N;
 
    # Calculate the upper
    # bound of K
    while (l < r):
 
        # Stores mid element
        # of l and r
        mid = (l + r) // 2;
 
        # If arr[mid] is less
        # than or equal to K
        if (arr[mid] <= K):
 
            # Right subarray
            l = mid + 1;
        else:
 
            # Left subarray
            r = mid;
    return l;
 
# Function to prall array elements
# whose frequency is greater than N / K
def NDivKWithFreq(arr, N, K):
   
  # Sort the array arr
    arr.sort();
 
    # Stores index of
    # an array element
    i = 0;
 
    # Traverse the array
    while (i < N):
 
        # Stores upper bound of arr[i]
        X = upperBound(arr, N, arr[i]);
 
        # If frequency of arr[i] is
        # greater than N / 4
        if ((X - i) > N // 4):
            print(arr[i], end="");
 
        # Update i
        i = X;
 
# Driver Code
if __name__ == '__main__':
   
    # Given array arr
    arr = [1, 2, 2, 6, 6, 6, 6, 7, 10];
 
    # Size of array
    N = len(arr);
    K = 4;
 
    # Function Call
    NDivKWithFreq(arr, N, K);
 
    # This code is contributed by 29AjayKumar

C#

// C# program to implement
// the above approach
using System;
class GFG
{
 
  // Function to+ find the upper_bound of
  // an array element
  static int upperBound(int []arr, int N, int K)
  {
 
    // Stores minimum index
    // in which K lies
    int l = 0;
 
    // Stores maximum index
    // in which K lies
    int r = N;
 
    // Calculate the upper
    // bound of K
    while (l < r)
    {
 
      // Stores mid element
      // of l and r
      int mid = (l + r) / 2;
 
      // If arr[mid] is less
      // than or equal to K
      if (arr[mid] <= K)
      {
 
        // Right subarray
        l = mid + 1;
      }
 
      else
      {
 
        // Left subarray
        r = mid;
      }
    }
    return l;
  }
 
  // Function to print all array elements
  // whose frequency is greater than N / K
  static void NDivKWithFreq(int []arr, int N, int K)
  {
 
    // Sort the array arr[]
    Array.Sort(arr);
 
    // Stores index of
    // an array element
    int i = 0;
 
    // Traverse the array
    while (i < N)
    {
 
      // Stores upper bound of arr[i]
      int X = upperBound(arr, N, arr[i]);
 
      // If frequency of arr[i] is
      // greater than N / 4
      if ((X - i) > N / 4)
      {
 
        Console.Write(arr[i] + " ");
      }
 
      // Update i
      i = X;
    }
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
 
    // Given array arr[]
    int []arr = { 1, 2, 2, 6, 6, 6, 6, 7, 10 };
 
    // Size of array
    int N = arr.Length;
    int K = 4;
 
    // Function Call
    NDivKWithFreq(arr, N, K);
  }
}
 
// This code is contributed by AnkThon

Javascript


输出:
6

时间复杂度: O(N * log 2 N)
辅助空间: O(1)

另一种方法:使用内置Python函数:

  • 使用Counter()函数计算每个元素的频率。
  • 遍历频率数组并打印出现次数超过 n/k 次的所有元素。

下面是实现:

蟒蛇3

# Python3 implementation
from collections import Counter
 
# Function to find the number of array
# elements with frequency more than n/k times
def printElements(arr, n, k):
 
    # Calculating n/k
    x = n//k
 
    # Counting frequency of every
    # element using Counter
    mp = Counter(arr)
     
    # Traverse the map and print all
    # the elements with occurrence atleast n/k times
    for it in mp:
        if mp[it] > x:
            print(it)
 
 
# Driver code
arr = [1, 2, 2, 6, 6, 6, 6, 7, 10]
 
# Size of array
n = len(arr)
k = 4
 
printElements(arr, n, k)
 
# This code is contributed by vikkycirus

输出:

6

时间复杂度: O(N)

辅助空间: O(N)

高效方法:为了优化上述方法,其思想是将每个不同的数组元素的频率存储到一个 Map 中。最后,遍历地图并检查其频率是否大于(N / K) 。如果发现为真,则打印数组元素。有关此方法的讨论,请参阅本文。

时间复杂度: O(N)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程