Find the k most common elements in an integer array

Given an array A with possible duplicate entries, find the most important entries k.

My approach:

Create a MinHeap from the k most common elements sorted by frequency. the upper element is apparently the least found for the remaining elements. Create a HashMap to track all element counts and whether they are in MinHeap or not.

When reading a new integer:

  • check if it is in HashMap: increase the score in HashMap
  • also if it checks if it is on the heap: then increment the counter and heapify.
  • if not, then compare with the root element count and remove the root to add it if necessary. Then heapify.

At the end, return MinHeap as the desired output.

class Wrapper{
 boolean inHeap;
 int count;
}

O (n + k) O (n log k). / .

+4
8

, O(n), , O(2n) = O(n) .


HashMap.

, HashMap, .

, quickselect, k -th k ( k quickselect , ).

k, .

O(n) O(n + k log k), .

O(n).

+7

@Dukeling. ++ , quickselect.

:

:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <map>

using namespace std;

map<int,int> m;

void swap(int *a,int *b){
    int temp=*a;
    *a=*b;
    *b=temp;
}

void printelements(vector<int> &temp,int k){
    for(int i=0;i<=k;++i){
        cout<<temp[i]<<endl;
    }
} 

int partition(vector<int> &a, int low,int high){
    int pivot = high-1;
    int i=low-1;
    for(int j=low;j<high-1;j++){
        if(m[a[j]]>=m[a[pivot]]){
            i++;
            swap(&a[i],&a[j]);
        }
    }
    i++;
    swap(&a[i],&a[pivot]);
    return i;
}

void quickselect(vector<int> &temp,int low,int high,int k){
    if(low>high){
        return ;
    }
    int pivot=partition(temp,low,high);
    if(k==pivot){
        printelements(temp,k);
        return;
    }
    else if(k<pivot){
        quickselect(temp,low,pivot,k);
    }
    else{
        quickselect(temp,pivot+1,high,k);
    }
}

void topKelements(int a[],int n,int k){
    if(k<0)return ;
    for(int i=0;i<n;i++){
        if(m.find(a[i])!=m.end()){
            m[a[i]]++;
        }
        else{
            m.insert(pair<int,int>(a[i],1));
        }
    }
    vector<int> temp;
    map<int,int>::iterator it;
    for(it=m.begin();it!=m.end();++it){
        temp.push_back(it->first);
    }
    k=min(k,(int)temp.size()-1);
    quickselect(temp,0,temp.size(),k);
}

int main() {
    int a[] = {1,2,3,4,1,1,2,3,4,4,4,1};
    int k = 2;
    topKelements(a,12,k-1);
}

: 1 4 2

+3

, ​​ . , , Space Saving ( Lossy Count ).

O (n) k + 1 , k , $n $.

+1

, . int, , /count/numbers. . ( 1 ), 2x (1 ​​). , , 2 .

0

, . MergeSort (O(k log k) time), HashMap (O(n) time)). O(n + k*log(k)) = O(k*log(k)).

0

, , log (k) ? , , node , . , O (nk) .

(, TreeMap), log (k) . , .

0
public class ArrayProblems {
    static class Pair {
        int value;
        int count;

        Pair(int value, int count) {
           this.value = value;
           this.count = count;
       }
    }
/*
 * Find k numbers with most occurrences in the given array
 */
public static void mostOccurrences(int[] array, int k) {
    Map<Integer, Pair> occurrences = new HashMap<>();
    for(int element : array) {
        int count = 1;
        Pair pair = new Pair(element, count);
        if(occurrences.containsKey(element)) {
            pair = occurrences.get(element);
            pair.count++;
        }
        else {
            occurrences.put(element, pair);
        }
    }

    List<Pair> pairs = new ArrayList<>(occurrences.values());
    pairs.sort(new Comparator<Pair>() {
        @Override
        public int compare(Pair pair1, Pair pair2) {
            int result = Integer.compare(pair2.count, pair1.count);
            if(result == 0) {
                return Integer.compare(pair2.value, pair1.value);
            }
            return result;
        }
    });

    int[] result = new int[k];
    for(int i = 0; i < k; i++) {
        Pair pair = pairs.get(i);
        result[i] = pair.value;
    }

    System.out.println(k + " integers with most occurence: " + Arrays.toString(result));

}

public static void main(String [] arg)
{
    int[] array  = {3, 1, 4, 4, 5, 2, 6, 1};
    int k = 6;
    ArrayProblems.mostOccurrences(array, k);

    // 3 --> 1
    // 1 --> 2
    // 4 --> 2
    // 5 --> 1
    // 2 --> 1
    // 6 --> 1
}

}

0

hashmap. , . , -, k .

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;

    public class MaxRepeating
    {
        static void maxRepeating(int arr[], int n, int k)
        {
            Map<Integer,Integer> map=new HashMap<Integer,Integer>();
            // increment value in map if already present
            for (int i = 0; i< n; i++){
                map.put(arr[i], map.getOrDefault(arr[i], 0)+1);

            }
            map.entrySet().stream()
                    .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
                       .limit(k).forEach(System.out::println);

        }

        /*Driver function to check for above function*/
        public static void main (String[] args)
        {

            int arr[] = {7, 10, 11, 5, 2, 5, 5, 7, 11, 8, 9};
            int n = arr.length;
            int k=4;
            maxRepeating(arr,n,k);
        }
    }
0

Source: https://habr.com/ru/post/1543148/


All Articles