一个简单的算法题目

1)输入是List<Person>有id,age,height三个字段

2)输出也是List<Person>,其中同样年龄的只输出身高最高的,年龄身高都相同的,只输出id最大的。

public class Test {

    public static void main(String[] args) {
        List<Person> list = new ArrayList<>();
        list.add(new Person(2, 10, 170));
        list.add(new Person(1, 12, 180));
        list.add(new Person(1, 10, 170));
        list.add(new Person(6, 12, 180));
        list.add(new Person(2, 12, 175));
        System.out.println(list);
        
        System.out.println("-----------------");
        List<Person> returnValue = filter(list);
        returnValue.forEach(x -> System.out.println(x));
    }

    public static List<Person> filter(List<Person> list) {
        Map<Integer, PriorityQueue<Person>> map = new HashMap<>();
        for (int i = 0; i < list.size(); i++) {
            Person person = list.get(i);
            PriorityQueue<Person> temp = map.get(person.getAge());
            if (temp == null) {
                temp = new PriorityQueue<>((o1, o2) -> {
                    if (o1.getHeight() - o2.getHeight() < 0) {
                        return 1;
                    } else if (o1.getHeight() - o2.getHeight() == 0) {
                        return -(o1.getId() - o2.getId());
                    } else {
                        return -1;
                    }
                });
            }
            temp.add(person);
            map.put(person.getAge(), temp);
        }
        List<Person> returnList = new ArrayList<>();
        map.entrySet().forEach(x -> returnList.add(x.getValue().poll()));
        
        return returnList;
    }
}

输出结果:

[{age=10, height=170, id=2}, {age=12, height=180, id=1}, {age=10, height=170, id=1}, {age=12, height=180, id=6}, {age=12, height=175, id=2}]
-----------------
{age=10, height=170, id=2}
{age=12, height=180, id=6}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值