LC.P870[优势洗牌]

方法一:贪心+排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int[] advantageCount(int[] nums1, int[] nums2) {
int n = nums1.length;
Arrays.sort(nums1);
int[] ans = new int[n];
Integer[] index = new Integer[n];
for (int i = 0; i < n; ++i) index[i] = i;
Arrays.sort(index, (a, b) -> nums2[a] - nums2[b]);
int left = 0, right = n - 1;
for (int num : nums1) {
ans[num > nums2[index[left]] ? index[left++] : index[right--]] = num;
}
return ans;
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$