LeetCode每日一题(2449. Minimum Number of Operations to Make Arrays Similar)

给定两个等长的正整数数组nums和target,每次操作可以选择两个不同索引i和j,将nums[i]加2并使nums[j]减2。如果两个数组中每个元素的频率相同,则认为它们是相似的。该程序旨在找出使nums变得与target相似所需的最小操作次数。实现中涉及对数组进行排序,然后分别处理奇数和偶数,计算每个元素变为目标值的代价并求和。
摘要由CSDN通过智能技术生成

You are given two positive integer arrays nums and target, of the same length.

In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:

set nums[i] = nums[i] + 2 and
set nums[j] = nums[j] - 2.
Two arrays are considered to be similar if the frequency of each element is the same.

Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.

Example 1:

Input: nums = [8,12,6], target = [2,14,10]
Output: 2

Explanation: It is possible to make nums similar to target in two operations:

  • Choose i = 0 and j = 2, nums = [10,12,4].
  • Choose i = 1 and j = 2, nums = [10,14,2].
    It can be shown that 2 is the minimum number of operations needed.

Example 2:

Input: nums = [1,2,5], target = [4,1,3]
Output: 1

Explanation: We can make nums similar to target in one operation:

  • Choose i = 1 and j = 2, nums = [1,4,3].

Example 3:

Input: nums = [1,1,1,1,1], target = [1,1,1,1,1]
Output: 0

Explanation: The array nums is already similiar to target.

Constraints:

  • n == nums.length == target.length
  • 1 <= n <= 105
  • 1 <= nums[i], target[i] <= 106
  • It is possible to make nums similar to target.

  1. 因为加和减是对称的, 所以我们只需要统计一种即可
  2. num 与 target 都进行排序, 排序后, 对于 num[i], 一定是变成 target[i]的成本最低
  3. 注意奇偶的问题, 因为无论加减操作数都是 2, 所以奇数只能变成奇数,偶数只能变成偶数


impl Solution {
    pub fn make_similar(mut nums: Vec<i32>, mut target: Vec<i32>) -> i64 {
        nums.sort();
        let mut num_odds = Vec::new();
        let mut num_evens = Vec::new();
        for n in nums {
            if n % 2 == 0 {
                num_evens.push(n);
                continue;
            }
            num_odds.push(n);
        }
        target.sort();
        let mut target_odds = Vec::new();
        let mut target_evens = Vec::new();
        for n in target {
            if n % 2 == 0 {
                target_evens.push(n);
                continue;
            }
            target_odds.push(n);
        }
        let mut ans = 0;
        for (s, t) in num_odds.into_iter().zip(target_odds) {
            ans += if s > t { (s - t) as i64 / 2 } else { 0 };
        }
        for (s, t) in num_evens.into_iter().zip(target_evens) {
            ans += if s > t { (s - t) as i64 / 2 } else { 0 };
        }
        ans
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值