📌  相关文章
📜  数组元素频率范围查询的Java程序

📅  最后修改于: 2022-05-13 01:55:49.911000             🧑  作者: Mango

数组元素频率范围查询的Java程序

给定一个包含 n 个非负整数的数组。任务是在 array[] 的任意范围内找到特定元素的频率。范围作为数组中的位置(不是基于 0 的索引)给出。可以有多个给定类型的查询。
例子:

Input  : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
         left = 2, right = 8, element = 8
         left = 2, right = 5, element = 6      
Output : 3
         1
The element 8 appears 3 times in arr[left-1..right-1]
The element 6 appears 1 time in arr[left-1..right-1]

天真的方法:是从左到右遍历并在找到元素时更新计数变量。
以下是 Naive 方法的代码:-

Java
// JAVA Code to find total count of an element
// in a range
  
class GFG {
      
    // Returns count of element in arr[left-1..right-1]
    public static int findFrequency(int arr[], int n, 
                                int left, int right,
                                      int element)
    {
        int count = 0;
        for (int i = left - 1; i < right; ++i)
            if (arr[i] == element)
                ++count;
        return count;
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
        int n = arr.length;
       
        // Print frequency of 2 from position 1 to 6
        System.out.println("Frequency of 2 from 1 to 6 = " +
             findFrequency(arr, n, 1, 6, 2));
       
        // Print frequency of 8 from position 4 to 9
        System.out.println("Frequency of 8 from 4 to 9 = " +
             findFrequency(arr, n, 4, 9, 8));
          
    }
  } 
// This code is contributed by Arnav Kr. Mandal.


输出:

Frequency of 2 from 1 to 6 = 1
 Frequency of 8 from 4 to 9 = 2

这种方法的时间复杂度是 O(right – left + 1) 或 O(n)
辅助空间:O(1)
有关更多详细信息,请参阅有关数组元素频率的范围查询的完整文章!