Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- T.C O(n*k) S.C O(K+1)
- Logic:
- we will create a top vector of k+1 length where 0 to k-1th index will store the top k most frequent numbers and
- in descending order of frequency and a map which will store the frequency of whole array.
- Traverse the whole array:
- ->The last position of top vector is of no use so we will put the current element and increase it's frequency in map.
- ->before current element,we had k most frequent elements at top from 0 to k-1th index,so now frequency of current element
- is increase by 1 so there is only 2 possibility,either current element will be in top k most frequent or not.
- ->So we will find the first position of current element in top array because frequency incremented in only current element
- so only current element can go it's left only so we will start swapping the elements from j to 0 on the basis of frequency
- in decreasing order,this will surely adjust current element at it's orginal position as per frequency,even one iteration
- is enough for one element adjustment so rest element is already at their position as per frequency,only current element
- frequency is updated.
- */
- class Solution
- {
- public:
- vector<int> kTop(int arr[], int n, int k)
- {
- vector <int> top(k+1,0);
- unordered_map<int,int> mp;
- vector <int> ans;
- for(int i=0;i<n;i++){
- top[k]=arr[i];
- mp[top[k]]++;
- int j=0;
- for(j=0;j<k;j++){ //we have not started swapping from k to 0 because there is possibility that
- if(top[j]==arr[i]) break; //current element is already in top k element so get the first index of current element
- }
- while(j>0){
- if(mp[top[j]]>mp[top[j-1]]) swap(top[j],top[j-1]);
- if(mp[top[j]]==mp[top[j-1]] && top[j]<top[j-1]) swap(top[j],top[j-1]);//if frequency same,keeping numbers in decreasing order
- j--;
- }
- for(int l=0;l<k && top[l]!=0;l++) ans.push_back(top[l]);//pushing first k elements in result array and breaking the loop if top size is less than k.
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement