Tuesday, January 13, 2015

K most frequent numbers in an array -- PG first round phone

Question:

list of n integers:
1, 2, 3, 3, 3, 2, 4, 5, 5, 1

find k most frequent numbers:
k = 1:    3
k = 2:    3, 5 or 3, 2 or 3, 1
k = 3:    3, 5, 2 or 3, 5, 1 or 3, 2, 1

Answer:

time complexity = O(n * log(n))

class wrapper{
  int number;
  int freq;

public:
  wrapper(int i, int j){
    number = i;
    freq = j;
}

struct cmp{
  bool operator(wrapper lhs, wrapper rhs){
     if(lhs.freq < rhs.freq) return true;
  }
}

vector<int> mostFrequent(vector<int> arr, int k){
    int len = arr. length();
 
    unordered_map<int, int> mmap;
    for(int i=0;i<len;++i){
       if(mmap.find(arr[i]) == mmap.end()){
          mmap[arr[i]] = 0;
       }
       mmap[arr[i]] ++;
    }
 
    vector<wrapper> warr;
    vector<int> res;
    priority_queue<wrapper, vector<wrapper>, cmp> pq;
 
    for(int i=0;i<len;i++){
       if(mmap.find(arr[i])!= mmap.end()){
          wrapper wa = new wrapper(arr[i], mmap[arr[i]]);
          pq.push(wa);                                  //log n
          mmap.delete(arr[i]);
        }
    }
 
    for(int j=0;j<k;++j){
       wrapper tmp = pq.top();                   //log n
       pq.pop();
       res.push_back(tmp.number);
    }
    return res;
}

No comments:

Post a Comment