arrays - 两个总和 : Elements in 2 arrays equal predetermined Sum Swift 3

标签 arrays swift

如果我有两个数组,想知道每个数组中的一个元素 (Int) 是否等于一个预定值 (Int),我该怎么做。我是 Swift 的新手,有点迷茫。

func twoSum(a:[Int], b:[Int], c: Int) -> Bool {
     // iterate through arrays to see if an element in each equal c
     return false // if no values equal the sum c 
}

twoSum(a: [1,3,4,5], b: [1,3,4,5], c: 10)

我不需要将数组转换为集合,但我想知道如何有效地遍历这两个数组。如果没有一堆 for 或 if 循环,我将如何做到这一点?

最佳答案

一个解决方案可以是这样的:

使用filter查看a是否包含bc中每个值的差异,如果它那么 filter 返回的数组不会为空并且该函数将返回 true 否则 false

func twoSum(a:[Int], b:[Int], c: Int) -> Bool {

        return !b.filter {a.contains(c-$0)}.isEmpty

}

关于arrays - 两个总和 : Elements in 2 arrays equal predetermined Sum Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46210248/

相关文章:

ios - 带有 SpriteKit 的 Swift 应用程序 : normal to have 30% CPU usage with only 5 nodes and no active processing?

ios - 当前 View Controller 在 Swift 中不起作用

php - PHP 中有从数组中提取 'column' 的函数吗?

arrays - ElasticSearch中的权限

php - 内部数组的 array_unique

swift - RxSwift 如何更好地刷新 BehaviourSubject?

ios - 检测您是否要使用新的 View Controller 或旧的 View Controller

ios - Places API 未为 iOS 启用,即使它已经启用

c - 从 C 中的 1 个输入行读取多个值

javascript - 如何在JavaScript中使用正则表达式通过组重复匹配子字符串?