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

📅  最后修改于: 2021-05-17 03:39:40             🧑  作者: Mango

给定大小为N且整数K的数组arr [] ,任务是查找出现次数超过(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;
 
    // Calulate 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;
 
    // Calulate 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;
 
    # Calulate 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;
 
    // Calulate 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


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;
 
    // Calulate 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;
 
    // Calulate 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;
 
    # Calulate 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;
 
    // Calulate 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
输出:
6

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

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

  • 使用Counter()函数计算每个元素的频率。
  • 遍历频率阵列并打印所有出现在n / k次以上的元素。

下面是实现:

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)

辅助空间: O(N)

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

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

想要从精选的最佳视频中学习和练习问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”