让说,我有一个int数组,我想找到一个对数的本阵,这对的总和等于一个数,像这样:查找与条件阵列对
func findPair(list: [Int], _ sum: Int) -> (Int, Int)? {
for i in 0..<list.count - 1{
for j in (i+1)..<list.count {
let sumOfPair = list[i] + list[j]
if sumOfPair == sum {
return (list[i], list[j])
}
}
}
return nil
}
第一个参数是一个Int数组,第二个参数是我们需要比较该数组中某些对的数字。
例如:
findPair([1,2,3,4,5], 7) // will return (2, 5), because 2 + 5 = 7
但是该算法的复杂度为为O(n^2)。
有没有更快的方法?
可能http://stackoverflow.com/questions/4720271/find-a-pair-of-的副本元素的数组,它的总和等于一个给定的数字 – ChatterOne