zoukankan      html  css  js  c++  java
  • 0870. Advantage Shuffle (M)

    Advantage Shuffle (M)

    题目

    Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] > B[i].

    Return any permutation of A that maximizes its advantage with respect to B.

    Example 1:

    Input: A = [2,7,11,15], B = [1,10,4,11]
    Output: [2,11,7,15]
    

    Example 2:

    Input: A = [12,24,8,32], B = [13,25,32,11]
    Output: [24,32,8,12]
    

    Note:

    1. 1 <= A.length = B.length <= 10000
    2. 0 <= A[i] <= 10^9
    3. 0 <= B[i] <= 10^9

    题意

    给定数组A和B,重排列A,使得相同下标A元素比B元素大的对数最多。

    思路

    贪心。记结果数组为res。先将B中元素及对应下标复制到新数组copyB中,排序A和copyB。从大到小遍历copyB,记当前值为B_MAX,对应下标为index,如果A中剩余元素中的最大值A_MAX大于B_MAX,那么res[index]=A_MAX,否则res[index]=A_MIN。


    代码实现

    Java

    class Solution {
        public int[] advantageCount(int[] A, int[] B) {
            int[] res = new int[A.length];
            int[][] copyB = new int[B.length][2];
            int minP = 0, maxP = A.length - 1;
    
            for (int i = 0; i < B.length; i++) {
                copyB[i][0] = B[i];
                copyB[i][1] = i;
            }
    
            Arrays.sort(A);
            Arrays.sort(copyB, (a, b) -> b[0] - a[0]);
    
            for (int i = 0; i < copyB.length; i++) {
                res[copyB[i][1]] = A[maxP] > copyB[i][0] ? A[maxP--] : A[minP++];
            }
    
            return res;
        }
    }
    
  • 相关阅读:
    站立会议第二天
    站立会议第一天
    Scrum_Sprint
    电梯演讲之加减乘除
    The group WHATEVER is formed today
    awk简介(使用方法)
    关于Java进程流程简介
    Bootstrap_导航
    Bootstrap_按钮工具栏
    Bootstrap_下拉菜单
  • 原文地址:https://www.cnblogs.com/mapoos/p/14574765.html
Copyright © 2011-2022 走看看