题目
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)
Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.
Example :
Input:
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
Note:
The length of A will be in the range [1, 30].
A[i] will be in the range of [0, 10000].
数组 A 的长度为 1 ~ 30, A 中元素为大小为 0 ~ 10000 的整数,求 A 是否可以拆分为两个子数组 B 和 C,且 B 和 C 中元素加和的平均值相等。
解题思路
假设 A 可以拆分成符合条件的 B、C,A、B、C 的长度分别为 n、i、n-i ,则sumA/n == sumB/i == sumC/(n-i)。
由于所有元素均为整数,所以 sumA、sumB、sumC 均为整数,则 sumB == sumAi/n 为整数,则 sumAi%n == 0。
由于 1<=n<=30,1<=i<=n/2<=15,所以可以通过 sumA*i%n == 0 先寻找可能符合条件的 i 。
在找到 i 后,可以求出 sumB ,用 isExist 方法来判断 A 中是否存在 i 个元素加和为 sumB 的子数组。
isExist 方法中,通过 sumB 逐一减去元素,i-1,并进行递归,若最后 sumB 和 i 同时减为 0 ,说明有 i 个元素加和为 sumB,否则说明 i 不符合条件。
代码实现
Runtime: 16 ms
Memory: 20.8 MB
func splitArraySameAverage(_ nums: [Int]) -> Bool {