[Swift]LeetCode170.兩數之和III - 數據結構設計 $ Two Sum III - Data structure design

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-eraxuuht-md.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Design and implement a TwoSum class. It should support the following operations:add and find.git

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.github

For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false微信


設計和實現一個TwoSum類。它應該支持如下操做:add和find。數據結構

add-將數字添加到內部數據結構。app

find-查找是否存在求和等於值的任何對數對。spa

例如,設計

add(1); add(3); add(5);
find(4) -> true
find(7) -> falsecode


12mshtm

 1 class Solution {
 2     var s:[Int] = [Int]()
 3     func add(_ number:Int)
 4     {
 5         s.append(number)
 6     }
 7     
 8     func 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 }
相關文章
相關標籤/搜索