Leetcode 870

给出两个数组,求出A数组的一个排列,使下标相同的对应数有尽量多的数满足A[i] > B[i]

 

这不就是田忌赛马嘛!

我们使用贪心的策略

如果田忌最快的马比对方最快的马快,就和他比,赢一场

否则就用田忌最慢的马去和对方最快的马去比

 

这个题目要输出排列,可以看下代码:

    public int[] advantageCount(int[] A, int[] B) {
        int len = A.length;
        Arrays.sort(A);
        //递减的一个优先队列
        int[] res = new int[len];
        Queue<int[]> q = new PriorityQueue<>((o1, o2) -> Integer.compare(o2[0], o1[0]));
        for (int i = 0; i < len; i++) q.add(new int[]{B[i], i});
        int l = 0, r = len - 1;
        while(!q.isEmpty()) {
            int[] poll = q.poll();
            int v = poll[0];
            int idx = poll[1];
            if (A[r] > v) {
                res[idx] = A[r];
                r--;
            } else {
                res[idx] = A[l];
                l++;
            }
        }
        return res;
    }

还有一种贪心的策略:  找到比对方的马快的最小的那个马

https://leetcode.com/problems/advantage-shuffle/discuss/149840/C%2B%2BJava-Greedy-Solution-Using-Map

主要学习一下treemap的用法

    public int[] advantageCount(int[] A, int[] B) {
        TreeMap<Integer, Integer> m = new TreeMap<>();
        for (int i : A) m.put(i, m.getOrDefault(i, 0) + 1);
        int[] res = new int[A.length];
        for (int i = 0; i < A.length; ++i) {
            Integer x = m.higherKey(B[i]);
            if (x == null) x = m.firstKey();
            m.put(x, m.get(x) - 1);
            if (m.get(x) == 0) m.remove(x);
            res[i] = x;
        }
        return res;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值