[Swift]LeetCode170.兩數之和之三 - 資料結構設計 $ Two Sum III - Data structure design
阿新 • • 發佈:2018-12-16
Design and implement a TwoSum class. It should support the following operations:add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
設計和實現一個TwoSum類。它應該支援以下操作:add和find。
add-將數字新增到內部資料結構。
find-查詢是否存在求和等於值的任何對數對。
例如,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
12ms
1 class Solution { 2 var s:[Int] = [Int]() 3 func add(_ number:Int) 4 { 5 s.append(number) 6 } 7 8func find(_ value:Int) -> Bool 9 { 10 for a in s 11 { 12 var cnt:Int = 0 13 if a == (value - a) 14 { 15 cnt = 1 16 } 17 else 18 { 19 cnt = 0 20 }21 if count(value - a) > cnt 22 { 23 return true 24 } 25 } 26 return false 27 } 28 29 //統計某個值出現的次數 30 func count(_ num:Int) -> Int 31 { 32 var number:Int = 0 33 for i in s 34 { 35 if num == i 36 { 37 number += 1 38 } 39 } 40 return number 41 } 42 }