在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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:
给定的整数数组 A ,我们要将 A数组 中的每个元素移动到 B数组 或者 C数组中。(B数组和C数组在开始的时候都为空) 返回 示例: 输入: [1,2,3,4,5,6,7,8] 输出: true 解释: 我们可以将数组分割为 [1,4,5,8] 和 [2,3,6,7], 他们的平均值都是4.5。 注意:
20ms 1 class Solution { 2 func splitArraySameAverage(_ nums: [Int]) -> Bool { 3 let sum = nums.reduce(0, +) 4 let nums = nums.sorted() 5 let n = nums.count 6 if n < 2 { return false } 7 for i in 1...n / 2 where (sum * i) % n == 0 && dfs(nums, i, 0, sum * i / n) { return true } 8 return false 9 } 10 11 func dfs(_ nums: [Int], _ len: Int, _ idx: Int, _ sum: Int) -> Bool { 12 if sum == 0, len == 0 { return true } 13 if idx >= nums.count || len < 0 || sum < 0 { return false } 14 for i in idx..<nums.count { 15 if i > idx && nums[i] == nums[i - 1] { continue } 16 if dfs(nums, len - 1, i + 1, sum - nums[i]) { return true } 17 } 18 return false 19 } 20 } Runtime: 604 ms
Memory Usage: 24.9 MB
1 class Solution { 2 func splitArraySameAverage(_ A: [Int]) -> Bool { 3 if A.count < 2 {return false} 4 var sum:Int = A.reduce(0,+) 5 var n:Int = A.count 6 var m:Int = n / 2 7 var possible:Bool = false 8 var i:Int = 0 9 while(i <= m && !possible) 10 { 11 if sum * i % n == 0 {possible = true} 12 i += 1 13 } 14 if !possible {return false} 15 var dp:[Set<Int>] = [Set<Int>](repeating:Set<Int>(),count:m + 1) 16 dp[0].insert(0) 17 for num in A 18 { 19 for i in stride(from:m,through:1,by:-1) 20 { 21 for a in dp[i - 1] 22 { 23 dp[i].insert(a + num) 24 } 25 } 26 } 27 for i in 1...m 28 { 29 if sum * i % n == 0 && dp[i].contains(sum * i / n) 30 { 31 return true 32 } 33 } 34 return false 35 } 36 }
|
请发表评论