Beginner Swift 3: How to find pairs in array that add up to given number

前端 未结 4 1904
深忆病人
深忆病人 2021-01-22 05:40

Need to loop through an array and say whether there are any pairs of numbers that sum to 8

e.g. [1,2,4,4] = yes

Can get it working with lots of nested if stateme

4条回答
  •  独厮守ぢ
    2021-01-22 06:32

    Using two pointer technique.

    Time Complexity: O(n)

    Other solutions mentioned here have Time Complexity: O(n2)

    func isPairSum()-> Bool{
    
    let array = [3, 5, 9, 2, 8, 10, 11]
    let sum = 22
    
    
    var i = 0
    var j = array.count - 1
    
    while i sum {
            j -= 1
        }
        
        else if valueSum < sum {
            i += 1
        }
        
    }
    return false
    

    }

    And If you want the values of the pair, instead of returning Bool, you can return Tuple of type Int.

提交回复
热议问题