算法题:870. 优势洗牌

编程入门 行业动态 更新时间:2024-10-27 21:18:10

<a href=https://www.elefans.com/category/jswz/34/1770096.html style=算法题:870. 优势洗牌"/>

算法题: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]pareTo(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

 

更多推荐

算法题:870. 优势洗牌

本文发布于:2023-11-16 23:37:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634962.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   优势

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!