【算法】Split Array With Same Average 拆分数组为两个平均值的子数组

【算法】Split Array With Same Average 拆分数组为两个平均值的子数组

题目

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 {
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值