算法题:870. 优势洗牌
  DosddciaWHNX 2023年12月06日 19 0


该算法是临时想出来的,Java代码的实现在时间上不占优,之后有时间要优化一下,目前就是给大家提供一下思路。

算法题:870. 优势洗牌_Java

解题思路:田忌赛马的思想 + 贪心法。

Step1. 对两个数组进行排序。

Step2. 同时遍历排序后的nums2和nums1,将num1中刚好超过nums2当前值的值放到对应的位置,而不超过nums2当前值的值放到最后面去,因为反正这些值超不过nums2,不如把num1中较小的值用来对应nums2中较大的值。

Java代码

import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;

public class AdvantageCount {

    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(Arrays.toString(sol.advantageCount(new int[]{2,7,11,15}, new int[]{1,10,4,11})));
        System.out.println(Arrays.toString(sol.advantageCount(new int[]{12,24,8,32}, new int[]{13,25,32,11})));
    }
}

class ArrayIndexComparator implements Comparator<Integer> {
    private final Integer[] A;

    public ArrayIndexComparator(Integer[] arr) {
        this.A = arr;
    }

    public int compare(Integer o1, Integer o2) {
        return A[o1].compareTo(A[o2]);
    }
}

class Solution {
    public int[] advantageCount(int[] nums1, int[] nums2) {

        int n = nums1.length;
        // int[] -> Integer[]
        Integer[] nums2Integers =  Arrays.stream(nums2).boxed().toArray(Integer[]::new);
        // 排序后返回原索引
        Integer[] nums2Indexs = new Integer[n];
        IntStream.range(0, n).forEach(val -> nums2Indexs[val] = val);
        Arrays.sort(nums2Indexs, new ArrayIndexComparator(nums2Integers));

        int[] new_nums1 = new int[n];
        Arrays.sort(nums1);

        int j = 0;
        int k = n - 1;
        for (int i = 0; i < n; i++) {
            while(j < n && nums1[j] <= nums2[nums2Indexs[i]]){
                new_nums1[nums2Indexs[k]] = nums1[j];
                k--;
                j++;
            }
            if(j < n){
                new_nums1[nums2Indexs[i]] = nums1[j];
                j++;
            }
        }
        return new_nums1;
    }
}

完整题目

870. 优势洗牌

给定两个长度相等的数组 nums1 和 nums2nums1 相对于 nums2 的优势可以用满足 nums1[i] > nums2[i] 的索引 i 的数目来描述。

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

示例 1:

输入:nums1 = [2,7,11,15], nums2 = [1,10,4,11]
输出:[2,11,7,15]

示例 2:

输入:nums1 = [12,24,8,32], nums2 = [13,25,32,11]
输出:[24,32,8,12]

提示:

  • 1 <= nums1.length <= 10^5
  • nums2.length == nums1.length
  • 0 <= nums1[i], nums2[i] <= 10^9

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月06日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   53   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   107   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
DosddciaWHNX