如何解决稍后如何在PriorityQueue中隐式使用Set?
我从LeetCode的注释中得到了这个旧代码。我想了解一下,如果稍后不显式使用变量Set<Integer> set
,那么2个for循环在这里将做什么。我能猜到的最好的是,在以下情况下,记录中的值以某种方式从左向右引用到Set<Integer> set
:
Set<Integer> set = ((HashSet<Integer>) values[0]);
我以前从未见过这样的东西。因此,我想知道这是否与PriorityQueue
有关。我已经通过调试器进行了尝试,以更好地理解它,但是我能看到的最接近的引用也许是稍后将该值添加到队列中并出现在PriorityQueue
lambda中的时候。>
我删除了set.add(i)
,以为如果没有明确的参考,它什么也没做。我发现它确实会最终影响计数,并且预期的结果不是按此顺序。
class TopNCompetitors {
public static void main(String[] args) {
System.out.println(topNCompetitors(6,2,Arrays.asList("newshop","shopnow","afshion","fashionbeats","mymarket","tcellular"),6,Arrays.asList("newshop is providing good services in the city; everyone should use newshop","best services by newshop","fashionbeats has great services in the city","I am proud to have fashionbeats","mymarket has awesome services","Thanks Newshop for the quick delivery.")));
}
public static ArrayList<String> topNCompetitors(int numCompetitors,int topNCompetitors,List<String> competitors,int numReviews,List<String> reviews) {
ArrayList<String> ans = new ArrayList<>();
List<String[]> str = new ArrayList<>();
for (String review : reviews) {
str.add(review.trim().toLowerCase().replaceAll("[\\!?,;.]{1,}","").split("[ ]{1,}"));
}
Map<String,Object[]> records = new HashMap<>();
for (int i = 0; i < numCompetitors; i++) {
records.put(competitors.get(i).trim().toLowerCase(),new Object[]{new HashSet<Integer>(),competitors.get(i)});
}
for (int i = 0; i < numReviews; i++) {
String[] review = str.get(i);
for (int j = 0; j < review.length; j++) {
String in = review[j];
if (records.containsKey(in)) {
Object[] values = records.get(in);
Set<Integer> set = ((HashSet<Integer>) values[0]);
set.add(i);
}
}
}
Collection<Object[]> values = records.values();
PriorityQueue<Object[]> q = new PriorityQueue<>((t1,t2) -> {
int diff = ((Set<Integer>) t2[0]).size() - ((Set<Integer>) t1[0]).size();
if (diff == 0) {
return ((String) t1[1]).compareTo((String) t2[1]);
}
return diff;
});
for (Object[] val : values) {
q.add(val);
}
for (int i = 0; i < topNCompetitors; i++) {
ans.add((String) q.poll()[1]);
}
return ans;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。