[LeetCode] 2256. Minimum Average Difference
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 then
elements divided (integer division) byn
. - The average of
0
elements is considered to be0
.
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
最小平均差。
给你一个下标从 0 开始长度为 n 的整数数组 nums 。
下标 i 处的 平均差 指的是 nums 中 前 i + 1 个元素平均值和 后 n - i - 1 个元素平均值的 绝对差 。两个平均值都需要 向下取整 到最近的整数。
请你返回产生 最小平均差 的下标。如果有多个下标最小平均差相等,请你返回 最小 的一个下标。
注意:
两个数的 绝对差 是两者差的绝对值。
n 个元素的平均值是 n 个元素之 和 除以(整数除法) n 。
0 个元素的平均值视为 0 。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-average-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题的思路是前缀和。如果不知道前缀和,index 每移动一个位置,两个子数组的和的计算复杂度就会很高。
题意不难理解,我们需要遍历一遍整个数组。然后对于遍历到的每一个 index i,我们要看一下左半边子数组与右半边子数组的平均值,然后求二者的差值,最后返回的是全局最小的差值。计算的时候注意,即使是子数组,也有可能超过整型的范围,所以需要用long记录子数组的和,同时注意因为是求子数组的平均值,所以右半边求平均值的时候,如果分母为 0 则要特殊处理,直接视为右半边的平均值为 0。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int minimumAverageDifference(int[] nums) { 3 int len = nums.length; 4 long sum = 0; 5 for (int num : nums) { 6 sum += num; 7 } 8 9 int index = 0; 10 long min = Integer.MAX_VALUE; 11 long left = 0; 12 long right = 0; 13 for (int i = 0; i < len; i++) { 14 left += nums[i]; 15 right = sum - left; 16 long leftAverage = left / (i + 1); 17 long rightAverage = (len - i == 1) ? 0 : right / (len - i - 1); 18 long diff = Math.abs(leftAverage - rightAverage); 19 if (diff < min) { 20 min = diff; 21 index = i; 22 } 23 } 24 return index; 25 } 26 }