-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAmazonQ1.java
More file actions
71 lines (60 loc) · 2.38 KB
/
AmazonQ1.java
File metadata and controls
71 lines (60 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.*;
public class AmazonQ1 {
// Let's sort the hashmap
private static HashMap<String, Integer> sortByValue(SortedMap<String, Integer> map)
{
List<Map.Entry<String, Integer> > list =
new LinkedList<Map.Entry<String, Integer> >(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2)
{
return (o2.getValue()).compareTo(o1.getValue());
}
});
// put data from sorted list to hashmap
HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
// METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED
public ArrayList<String> topNCompetitors(int numCompetitors,
int topNCompetitors,
List<String> competitors,
int numReviews,
List<String> reviews) {
if (topNCompetitors <= 1) {
return new ArrayList<String>();
}
// WRITE YOUR CODE HERE
SortedMap<String, Integer> compMap = new TreeMap<String, Integer>();
for (String competitor : competitors) {
for (String review : reviews) {
String revLower = review.toLowerCase();
if (revLower.indexOf(competitor) != -1) {
Integer count = compMap.get(competitor);
if (count == null) {
compMap.put(competitor, 1);
} else {
compMap.put(competitor, count + 1);
}
}
}
}
Map<String, Integer> sortedMap = sortByValue(compMap);
// Compose final answer
int index = 0;
ArrayList<String> topComp = new ArrayList<>(topNCompetitors);
for (String compName : sortedMap.keySet()) {
topComp.add(index, compName);
index++;
if (index == topNCompetitors) {
break;
}
}
return topComp;
}
// METHOD SIGNATURE ENDS
}