LeetCode 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.
For example,
add(1); add(3); add(5); find(4) -> true find(7) -> false題解:
與Two Sum類似.
設(shè)計題目考慮trade off. 如果add 很多, find很少可以采用map方法.
簡歷HashMap保存key 和 key的frequency. find value時把HashMap的每一個key當(dāng)成num1, 來查找HashMap是否有另一個value-num1的key.
num1 = value - num1時,檢查num1的frequency是否大于1.
Time Complexity: add O(1). find O(n). Space: O(n).
AC Java:
1 class TwoSum { 2 3 HashMap<Integer, Integer> hm; 4 5 /** Initialize your data structure here. */ 6 public TwoSum() { 7 hm = new HashMap<Integer, Integer>(); 8 } 9 10 /** Add the number to an internal data structure.. */ 11 public void add(int number) { 12 hm.put(number, hm.getOrDefault(number, 0) + 1); 13 } 14 15 /** Find if there exists any pair of numbers which sum is equal to the value. */ 16 public boolean find(int value) { 17 for(Map.Entry<Integer, Integer> entry : hm.entrySet()){ 18 int num1 = entry.getKey(); 19 int num2 = value-num1; 20 if(hm.containsKey(num2) && (hm.get(num2)>1 || num1!=num2)){ 21 return true; 22 } 23 } 24 return false; 25 } 26 } 27 28 /** 29 * Your TwoSum object will be instantiated and called as such: 30 * TwoSum obj = new TwoSum(); 31 * obj.add(number); 32 * boolean param_2 = obj.find(value); 33 */考慮到trade off, 上面用HashMap時add用O(1), find用O(n).
用兩個Set分別存現(xiàn)有nums 和現(xiàn)有sums可以treade off.
這種設(shè)計適合少量add, 多量find操作.
Time Complexity:?add O(n). find O(1). Space: O(n).
AC Java:
1 public class TwoSum { 2 HashSet<Integer> nums; 3 HashSet<Integer> sums; 4 5 /** Initialize your data structure here. */ 6 public TwoSum() { 7 nums = new HashSet<Integer>(); 8 sums = new HashSet<Integer>(); 9 } 10 11 /** Add the number to an internal data structure.. */ 12 public void add(int number) { 13 Iterator<Integer> it = nums.iterator(); 14 while(it.hasNext()){ 15 sums.add(it.next()+number); 16 } 17 nums.add(number); 18 } 19 20 /** Find if there exists any pair of numbers which sum is equal to the value. */ 21 public boolean find(int value) { 22 return sums.contains(value); 23 } 24 } 25 26 /** 27 * Your TwoSum object will be instantiated and called as such: 28 * TwoSum obj = new TwoSum(); 29 * obj.add(number); 30 * boolean param_2 = obj.find(value); 31 */?
轉(zhuǎn)載于:https://www.cnblogs.com/Dylan-Java-NYC/p/5324746.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode Two Sum III - Data structure design的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jdk与cglib的动态代理
- 下一篇: 用 openSSL 生成 公钥 私钥