LeetCode每日一题(2256. Minimum Average Difference)

本文介绍了一种通过计算数组中元素的前缀和来找到具有最小平均差值的索引的方法。具体实现中,利用前缀和避免了重复计算,并妥善处理了除数为零的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a 0-indexed integer array nums of length n.

The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.

Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.

Note:

The absolute difference of two numbers is the absolute value of their difference.
The average of n elements is the sum of the n elements divided (integer division) by n.
The average of 0 elements is considered to be 0.

Example 1:

Input: nums = [2,5,3,9,5,3]
Output: 3

Explanation:

  • The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.
  • The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.
  • The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.
  • The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.
  • The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.
  • The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.
    The average difference of index 3 is the minimum average difference so return 3.

Example 2:

Input: nums = [0]
Output: 0

Explanation:
The only index is 0 so return 0.
The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 105

比较简单的问题, 只要想到 prefix sum, 答案就出来了, 注意除以 0 的情况就好了



impl Solution {
    pub fn minimum_average_difference(nums: Vec<i32>) -> i32 {
        let prefix_sum: Vec<i64> = nums
            .into_iter()
            .scan(0, |s, v| {
                *s += v as i64;
                Some(*s)
            })
            .collect();
        let mut min = i64::MAX;
        let mut min_index = 0;
        for i in 0..prefix_sum.len() {
            let first = prefix_sum[i] / (i + 1) as i64;
            let second = if i != prefix_sum.len() - 1 {
                (*prefix_sum.last().unwrap() - prefix_sum[i]) / (prefix_sum.len() - i - 1) as i64
            } else {
                0
            }
            .abs();
            let diff = (first - second).abs();
            if diff < min {
                min = diff;
                min_index = i;
            }
        }
        min_index as i32
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值