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

前端 未结 4 1817
深忆病人
深忆病人 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:36

    You can use nested for loops with indexes:

    for (firstIndex, firstElement) in numbersSet.enumerated() {
        for (secondIndex, secondElement) in numbersSet.enumerated() {
            if firstIndex != secondIndex && firstElement + secondElement == 8 {
                return true
            }
        }
    }
    

提交回复
热议问题