如果我有两个数组,想知道每个数组中的一个元素 (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
是否包含b
和c
中每个值的差异,如果它那么 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/