You are given two arrays of integers nums1
and nums2
, possibly of different lengths. The values in the arrays are between 1
and 6
, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1
and 6
, inclusive.
Return the minimum number of operations required to make the sum of values in nums1
equal to the sum of values in nums2
. Return -1
if it is not possible to make the sum of the two arrays equal.
Example 1:
Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].
- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].
- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].
Example 2:
Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]
Output: -1
Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.
Example 3:
Input: nums1 = [6,6], nums2 = [1]
Output: 3
Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.
- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].
- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].
- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].
Constraints:
1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 6
题目大意:给两个值在[1,6]的数组,每次可以将两数组中任意一个数字变成[1,6]中的任何数,问最少变换几次可以使两个数组和相等
题目分析:显然当某个数组可能的最小值大于另一数组可能的最大值时无解,有解情况下的最优操作显然是取能将diff变的更小的操作,要么用和大的数组的大数字减小,要么用和小的数组的小数字增大,两个指针扫一下即可,这种做法需要排序
14ms, 时间击败68.85%
class Solution {
public int minOperations(int[] nums1, int[] nums2) {
int l1 = nums1.length, l2 = nums2.length;
int mi1 = l1, ma1 = l1 * 6, mi2 = l2, ma2 = l2 * 6;
if (mi1 > ma2 || mi2 > ma1) {
return -1;
}
int sum1 = 0, sum2 = 0;
for (int i = 0; i < l1; i++) {
sum1 += nums1[i];
}
for (int i = 0; i < l2; i++) {
sum2 += nums2[i];
}
if (sum1 == sum2) {
return 0;
}
if (sum1 < sum2) {
return minOperations(nums2, nums1);
}
int ans = 0;
Arrays.sort(nums1);
Arrays.sort(nums2);
// decrease sum1 and increase sum2
if (sum1 > sum2) {
int i = l1 - 1, j = 0, diff = sum1 - sum2;
while (i >= 0 && j < l2 && diff > 0) {
int val1 = nums1[i] - 1;
int val2 = 6 - nums2[j];
if (val1 > val2) {
i--;
diff -= val1;
} else {
j++;
diff -= val2;
}
ans++;
}
while (i >= 0 && diff > 0) {
diff -= nums1[i--] - 1;
ans++;
}
while (j < l2 && diff > 0) {
diff -= 6 - nums2[j++];
ans++;
}
}
return ans;
}
}
不需要排序的做法是直接存每个数字变成最大或最小值的diff,然后从5到1枚举计算即可