LeetCode -- 870. 优势洗牌
贪心:这种最大化类似于田忌赛马。
每次取出nums1中最小的,和nums2进行比较,如果打得过,就打;打不过就用当前最小的和nums2中最大的换掉
c ++
class Solution { public: vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) { int n = nums1.size(), ids[n]; vector<int> ans(n); sort(nums1.begin(), nums1.end()); iota(ids, ids + n, 0); sort(ids, ids + n, [&](int a, int b) { return nums2[a] < nums2[b]; }); int left = 0, right = n - 1; for(int x : nums1) { ans[x > nums2[ids[left]] ? ids[left ++ ]: ids[right -- ]] = x; } return ans; } };
python class Solution: def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]: n = len(nums1) ans = [0] * n nums1.sort() ids = sorted(range(n), key = lambda i: nums2[i]) left, right = 0, n - 1 for x in nums1: if x > nums2[ids[left]]: ans[ids[left]] = x left += 1 else: ans[ids[right]] = x right -= 1 return ans
java class Solution { public int[] advantageCount(int[] nums1, int[] nums2) { int n = nums1.length; var ans = new int[n]; Arrays.sort(nums1); var ids = IntStream.range(0, n).boxed().toArray(Integer[]::new); Arrays.sort(ids, (Integer i, Integer j) -> { return nums2[i] - nums2[j]; }); int left = 0, right = n - 1; for(int x : nums1) { ans[x > nums2[ids[left]] ? ids[left ++ ] : ids[right -- ]] = x; } return ans; } }
golang func advantageCount(nums1 []int, nums2 []int) []int { n := len(nums1) ans := make([]int, n) sort.Ints(nums1) ids := make([]int, n) for i := range ids { ids[i] = i } sort.Slice(ids, func(i, j int) bool { return nums2[ids[i]] < nums2[ids[j]] }) left, right := 0, n - 1 for _, x := range nums1 { if x > nums2[ids[left]] { ans[ids[left]] = x left ++ } else { ans[ids[right]] = x right -- } } return ans }
js /** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var advantageCount = function(nums1, nums2) { let n = nums1.length; let ans = new Array(n).fill(-1); let ids = new Array(n).fill(0).map((_, index) => { return index; }).sort((a, b) => { return nums2[a] - nums2[b]; }); nums1.sort((a, b) => { return a - b; }); let left = 0, right = n - 1; for(let x of nums1) { if(x > nums2[ids[left]]) { ans[ids[left]] = x; left ++ ; } else { ans[ids[right]] = x; right -- ; } } return ans; };