Last active
February 1, 2024 13:00
-
-
Save IhwanID/bf4dbe52528dd43960adb5b445d9f8a2 to your computer and use it in GitHub Desktop.
Given a set of numbers, determine if there is a pair that equals a given sum.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//func hasPairWithSum(_ arr: [Int], _ sum: Int) -> Bool { | |
// | |
// for i in 0..<arr.count { | |
// for j in i + 1..<arr.count { | |
// if arr[i] + arr[j] == sum { | |
// return true | |
// } | |
// } | |
// } | |
// return false | |
//} | |
func hasPairWithSum(_ arr: [Int], _ sum: Int) -> Bool { | |
var comp = Set<Int>() | |
for value in arr { | |
if comp.contains(value) { | |
return true | |
} | |
comp.insert(sum-value) | |
} | |
return false | |
} | |
hasPairWithSum([1,2,4,9], 8) //false | |
hasPairWithSum([1,2,4,4], 8) //true | |
hasPairWithSum([1,2,5,3], 8) //true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment