LeetCode·每日一题·1775.通过最少操作次数使数组的和相等·贪心
2023-09-27 14:26:29 时间
作者:小迅
链接:https://leetcode.cn/problems/equal-sum-arrays-with-minimum-number-of-operations/solutions/2010289/tan-xin-zhu-shi-chao-ji-xiang-xi-by-xun-tjs4r/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目![](https://img-blog.csdnimg.cn/6f5dfe57510546d0bb92b9e349c9b8ac.png)
示例![](https://img-blog.csdnimg.cn/e627a013a2d148018ddf99e189d24f0b.png)
思路
题意 -> 我们将两个数组中的任意元素进行变化,使得两个数组的和相等,返回最小的变化次数
对于最值问题我们使用贪心作为切入点,对于本题我们可以将所有元素进行累加,然后再变化具体元素时,我们每次都寻找最大或者最小值进行变化,这样可以使得每次的变化值能辐射的范围更大,也就更能匹配正确值。
我们不妨设 s1 > s2, 则两个数组的差值为d = s1 - s2。为了使操作次数最少,我们贪心的把nums1中比较大的数变成1,把对应的nums2中比较小的数变成6,每一次变化把答案+1,直到d小于等于0。当 d 小于 0 时,说明我们本次修改的辐射范围为 小于 0的位置,自然也就包含0
代码
int min_operations(int *cnt1, int *cnt2, int d)
{
int i, ans = 0;
for (i = 6; i > 1 && d > 0; i--) {
while (d > 0 && cnt1[i]) {//最大值变小
d -= i - 1;
cnt1[i]--;
ans++;
}
while (d > 0 && cnt2[7 - i]) {//最小值变大
d -= i - 1;
cnt2[7 - i]--;
ans++;
}
}
return ans;
}
int minOperations(int* nums1, int nums1Size, int* nums2, int nums2Size){
int i, d = 0, cnt1[7] = {0}, cnt2[7] = {0};
/* 无法使两个数组的和相等 */
if (nums1Size > 6 * nums2Size || nums2Size > 6 * nums1Size)
return -1;
for (i = 0; i < nums1Size; i++) {//累加nums1的前缀和
cnt1[nums1[i]]++;
d += nums1[i];
}
for (i = 0; i < nums2Size; i++) {//可以累加也可以相差
cnt2[nums2[i]]++;
d -= nums2[i];
}
if (d < 0)
return min_operations(cnt2, cnt1, -d);//返回修改操作数
return min_operations(cnt1, cnt2, d);
}
作者:小迅
链接:https://leetcode.cn/problems/equal-sum-arrays-with-minimum-number-of-operations/solutions/2010289/tan-xin-zhu-shi-chao-ji-xiang-xi-by-xun-tjs4r/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关文章
- JS Leetcode 852. 山脉数组的峰顶索引图解分析,高高的山峰一起吹山风吧。
- JS Leetcode 304. 二维区域和检索 - 矩阵不可变,彻底弄懂二维数组前缀和
- LeetCode 167. 两数之和 II - 输入有序数组
- 168、【动态规划】leetcode ——121. 买卖股票的最佳时机:dp数组+变量优化 (C++版本)
- 116、【回溯算法】leetcode ——17. 电话号码的字母组合:回溯法:哈希映射+字符串数组映射(C++版本)
- STL-vector(使用场景+leetcode题库常见操作总结)
- 【leetcode周赛记录】第76场双周赛+第289场周赛记录
- 【leetcode】日积月累,每日一题--26. 删除有序数组中的重复项(DayDayUp 11)【EDG加油】
- 【leetcode】力扣 --- 日积月累,每日一题——7 有序数组的平方
- [LeetCode] 1307. Verbal Arithmetic Puzzle 口算难题
- [LeetCode] 1299. Replace Elements with Greatest Element on Right Side 将每个元素替换为右侧最大元素
- [LeetCode] 1005. Maximize Sum Of Array After K Negations K次取反后最大化的数组和
- [LeetCode] 934. Shortest Bridge 最短的桥梁
- [LeetCode] 828. Count Unique Characters of All Substrings of a Given String 统计给定字符串的所有子串的独特字符
- [LeetCode] 904. Fruit Into Baskets 水果装入果篮
- [LeetCode] 898. Bitwise ORs of Subarrays 子数组按位或操作
- [LeetCode] 866. Prime Palindrome 质数回文数
- [LeetCode] Maximum Sum of 3 Non-Overlapping Subarrays 三个非重叠子数组的最大和
- [LeetCode] Find the Derangement of An Array 找数组的错排
- [LeetCode] Maximum Distance in Arrays 数组中的最大距离
- [LeetCode] 565. Array Nesting 数组嵌套
- [LeetCode] 532. K-diff Pairs in an Array 数组中差为K的数对
- [LeetCode] Patching Array 补丁数组
- [LeetCode] 189. Rotate Array 旋转数组
- [LeetCode] Excel Sheet Column Number 求Excel表列序号
- LeetCode将有序数组转换为二叉搜索树