【EASY】Two Sum III
发布于:2019-03-22 17:00,阅读数:487,点赞数:0
# 问题 原题链接:[https://leetcode.com/problems/two-sum-iii-data-structure-design/](https://leetcode.com/problems/two-sum-iii-data-structure-design/) 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. Example 1: ``` add(1); add(3); add(5); find(4) -> true find(7) -> false ``` Example 2: ``` add(3); add(1); add(2); find(3) -> true find(6) -> false ``` # 分析过程 - 输入:存入数据以及要查找的和 - 输出:是否能够找到相加等于目标的两个数 - 思路:主要解决的就是重复数的情况。使用字典保存数据,key 是数字,value 是个数。遍历时如果 value - num 和 value 相同,必须 value 的个数是两个以上才可以,否则就继续循环。 # 解决方法 ```swift class TwoSum { var nums = Dictionary<Int, Int>() /** Initialize your data structure here. */ init() { } /** Add the number to an internal data structure.. */ func add(_ number: Int) { if nums[number] != nil { nums[number]! += 1 } else { nums[number] = 1 } } /** Find if there exists any pair of numbers which sum is equal to the value. */ func find(_ value: Int) -> Bool { for (num, _) in nums { guard let count = nums[value - num] else { continue } if value - num == num { if count >= 2 { return true } } else { return true } } return false } } ```
评论:0条