网站广告位,常州网络推广网站,有哪些做统计销量的网站,改域名 wordpress该算法是临时想出来的#xff0c;Java代码的实现在时间上不占优#xff0c;之后有时间要优化一下#xff0c;目前就是给大家提供一下思路。 解题思路#xff1a;田忌赛马的思想 贪心法。
Step1. 对两个数组进行排序。
Step2. 同时遍历排序后的nums2和nums1#xff0c;将…该算法是临时想出来的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 ComparatorInteger {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^5nums2.length nums1.length0 nums1[i], nums2[i] 10^9