You have an array arr
of length n
where arr[i] = (2 * i) + 1
for all valid values of i
(i.e. 0 <= i < n
).
In one operation, you can select two indices x
and y
where 0 <= x, y < n
and subtract 1
from arr[x]
and add 1
to arr[y]
(i.e. perform arr[x] -=1
and arr[y] += 1
). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.
Given an integer n
, the length of the array. Return the minimum number of operations needed to make all the elements of arr equal.
Example 1:
Input: n = 3 Output: 2 Explanation: arr = [1, 3, 5] First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4] In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].Example 2:
Input: n = 6 Output: 9
Constraints:
1 <= n <= 10^4
使数组中所有元素相等的最小操作数。
题意是给一个数字N,代表一个长度为N的数组arr。数组中的数字arr[i] = (2 * i) + 1。一次操作中,你可以选出两个下标,记作 x 和 y ( 0 <= x, y < n )并使 arr[x] 减去 1 、arr[y] 加上 1 (即 arr[x] -=1 且 arr[y] += 1 )。最终的目标是使数组中的所有元素都相等。请问你至少需要几次操作可以将数组中的所有数字相等。
这道题不难,根据规则发现创建出来的数组长如下这样,是个等差数列。
index 0 1 2 3 4 5 6 7 8
num[index] 1 3 5 7 9 11 13 15 17
既然操作规则会同时涉及到两个数字,那么应该是把数组两边的数字往中间改,或者说改成数组的中位数比较合理。另外需要注意的是
如果N是奇数,就是直接改成中位数
如果N是偶数,可以试着将所有数字改成中间两个数的平均值
时间O(1) - 是有限次数的操作
空间O(1)
Java实现
1 class Solution { 2 public int minOperations(int n) { 3 int m = n / 2; 4 if (n % 2 == 1) { 5 return m * (m + 1); 6 } else { 7 return m * m; 8 } 9 } 10 }