📣 独立日限时特惠: VIP通行证立减$68
查看: 5319| 回复: 6
跳转到指定楼层
上一主题 下一主题
收起左侧

【求大神看代码】find k closest element

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 MASBOBO 于 2017-9-18 05:52 编辑

求大家帮看下代码,leetcode的658. Find K Closest Elements, 报错Line 5: error: <anonymous Solution$1> is not abstract and does not override abstract method compare(Integer,Integer) in Comparator。 但我看不出来是什么问题。。代码如下。                 
class Solution {
    int ori;
    public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
        ori = x;
        PriorityQueue<Integer> pq = new PriorityQueue <Integer> (k, new Comparator<Integer>(){
         @Override
         public int compare(int a, int b){
                int sub = Math.abs(b - ori) - Math.abs(a - ori);
                if(sub == 0){
                    sub = b - a;
                }
                return sub;
            }
        });
        for(int i = 0; i < arr.size(); i++){
            pq.offer(arr.get(i));
            if(pq.size() > k)
                pq.poll();
        }
        int [] res = new int [k];
        while(!pq.size() == 0){
            res[k-1] = pq.poll();
            k--;
        }
        List <Integer> list = new ArrayList<> ();
        for(int i = 0; i < k; i++){
            list.add(res);
        }
        return list;
    }
}


上一篇:坐标Menlo Park, 在职, 找小伙伴每周中晚上, 周末刷题
下一篇:找人刷题打卡
推荐
stellari 2017-9-20 02:17:46 | 只看该作者
全局:
其实错误信息说得很明确了,你需要override一个compare(Integer,Integer),而你却给的是compare(int, int)。这俩不是一回事。

另外,也不能用!pq.size()==0。!的优先级是高于==的。

回复

使用道具 举报

🔗
need_offer 2018-1-13 00:55:08 | 只看该作者
全局:
所以,楼主最后是怎么解决的?
回复

使用道具 举报

🔗
quanatm 2021-4-11 04:50:35 | 只看该作者
全局:
integer zszszs
回复

使用道具 举报

🔗
BobbyBear 2021-4-11 08:05:09 | 只看该作者
全局:
直接用anonymous function作为comparator吧,简单明了。
回复

使用道具 举报

🔗
Falldawn 2021-4-12 00:50:18 | 只看该作者
全局:
PriorityQueue<Integer> pq = new PriorityQueue <Integer> (k, new Comparator<Integer>(){
         @Override
         public int compare(int a, int b){
                int sub = Math.abs(b - ori) - Math.abs(a - ori);
                if(sub == 0){
                    sub = b - a;
                }
                return sub;
            }
        });

这个比较器写得不对,

PriorityQueue<Integer> pq = new PriorityQueue <Integer> (k, new Comparator<Integer>(){
         @Override
         public int compare(int a, int b){
                return Integer.compare(Math.abs(a - ori), Math.abs(b - ori));
            }
        });

补充内容 (2021-04-12 03:51 +8:00):
不好意思,要用Integer
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表