LeetCode 870. 优势洗牌

最近刷LeetCode题目的一些思路,题目信息

给定两个大小相等的数组 A 和 B,A 相对于 B 的优势可以用满足 A[i] > B[i] 的索引 i 的数目来描述。

返回 A 的任意排列,使其相对于 B 的优势最大化。

 

示例 1:

输入:A = [2,7,11,15], B = [1,10,4,11]
输出:[2,11,7,15]

示例 2:

输入:A = [12,24,8,32], B = [13,25,32,11]
输出:[24,32,8,12]

 

提示:

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

-------------------------------------------------------------------------------------- 

思路分析,其实真正的处理就是把A和B两个数组的数据进行排序, 从小到大开始处理,找出来B中最小的数据,然后取出来A中比它大的最小数据,放到对应位置,这样的出来的优势就是最大的,具体实现如下

1: A中所有数据放在一个List里面,然后进行排序

2:B中数据需要记录位置并且进行排序,所以需要一个TreeMap

3:按从小到大的顺序取TreeMap中的B数据,然后需要找到比当前数据大的A中最小的数据,然后放在A中与B中数据对应位置上,如果不存在比该数据大的,则取出来List中最小的数据放在A中与B中数据对应的位置

public int[] advantageCount(int[] A, int[] B) {
    List listA = new ArrayList<>();
    for(int i:A){
        listA.add(i);
    }
    Collections.sort(listA);
    Map> mapB = new TreeMap<>();
    for(int j = 0; j< B.length; j++){
        List childList = mapB.get(B[j]);
        if(childList == null){
            childList = new ArrayList<>();
        }
        childList.add(j);
        mapB.put(B[j],childList);
    }
    Iterator iterator = mapB.keySet().iterator();
    int n=0;
    while (iterator.hasNext()){
        int data = iterator.next();
        for(n = n; n data){
                break;
            }
        }
        List indexList = mapB.get(data);
        for(int index: indexList){
            if(n

你可能感兴趣的:(LeetCode)