稍后如何在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 (将#修改为@)