You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/* *
* F i l e : t w o _ s u m . s w i f t
* C r e a t e d T i m e : 2 0 2 3 - 0 1 - 0 3
* A u t h o r : n u o m i 1 ( n u o m i 1 @ q q . c o m )
*/
/* 方 法 一 : 暴 力 枚 举 */
func twoSumBruteForce ( nums : [ Int ] , target : Int ) -> [ Int ] {
// 两 层 循 环 , 时 间 复 杂 度 为 O ( n ^ 2 )
for i in nums . indices . dropLast ( ) {
for j in nums . indices . dropFirst ( i + 1 ) {
if nums [ i ] + nums [ j ] = = target {
return [ i , j ]
}
}
}
return [ 0 ]
}
/* 方 法 二 : 辅 助 哈 希 表 */
func twoSumHashTable ( nums : [ Int ] , target : Int ) -> [ Int ] {
// 辅 助 哈 希 表 , 空 间 复 杂 度 为 O ( n )
var dic : [ Int : Int ] = [ : ]
// 单 层 循 环 , 时 间 复 杂 度 为 O ( n )
for i in nums . indices {
if let j = dic [ target - nums [ i ] ] {
return [ j , i ]
}
dic [ nums [ i ] ] = i
}
return [ 0 ]
}
@ main
enum LeetcodeTwoSum {
/* D r i v e r C o d e */
static func main ( ) {
// = = = = = = = T e s t C a s e = = = = = = =
let nums = [ 2 , 7 , 11 , 15 ]
let target = 13
// = = = = = = D r i v e r C o d e = = = = = =
// 方 法 一
var res = twoSumBruteForce ( nums : nums , target : target )
print ( " 方法一 res = \( res ) " )
// 方 法 二
res = twoSumHashTable ( nums : nums , target : target )
print ( " 方法二 res = \( res ) " )
}
}