Most Popular Video Creator - Hashmap [JS]
Solution: Hashmap
In a hashmap, store the following for each person:
- The sum of views
- The id of the video with maximum views
- The maximum number of views
Then, go through each person and record the highest number of views and the people with the maximum views.
Time Complexity: O(n)
725ms
Space Complexity: O(n)
144.6MB
var mostPopularCreator = function(creators, ids, views) {
let n = creators.length, map = {}; // { creator: [sum of views, maxId, maxViews] }
for (let i = 0; i < n; i++) {
let creator = creators[i];
if (!map[creator]) map[creator] = [views[i], ids[i], views[i]];
else {
map[creator][0] += views[i];
let [_, maxId, maxViews] = map[creator];
if (views[i] > maxViews) {
map[creator][2] = views[i];
map[creator][1] = ids[i];
} else if (views[i] === maxViews) {
map[creator][1] = ids[i] < maxId ? ids[i] : maxId;
}
}
}
let bestCreators = [], maxViews = 0;
for (let creator in map) {
let totalViews = map[creator][0];
if (totalViews > maxViews) {
maxViews = totalViews;
bestCreators = [[creator, map[creator][1]]];
} else if (totalViews === maxViews) {
bestCreators.push([creator, map[creator][1]]);
}
}
return bestCreators;
};
Comments
Post a Comment