1+ package com .leetcode .maps ;
2+
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+
6+ import static org .junit .jupiter .api .Assertions .assertTrue ;
7+
8+ /**
9+ * Level: Easy
10+ * Problem Link: https://leetcode.com/problems/two-sum-iii-data-structure-design/
11+ * Problem Description:
12+ * Design and implement a TwoSum class. It should support the following operations: add and find.
13+ * <p>
14+ * add - Add the number to an internal data structure.
15+ * find - Find if there exists any pair of numbers which sum is equal to the value.
16+ * <p>
17+ * Example 1:
18+ * add(1); add(3); add(5);
19+ * find(4) -> true
20+ * find(7) -> false
21+ * <p>
22+ * Example 2:
23+ * add(3); add(1); add(2);
24+ * find(3) -> true
25+ * find(6) -> false
26+ *
27+ * @author rampatra
28+ * @since 2019-08-03
29+ */
30+ public class TwoSumIII {
31+
32+ Map <Integer , Integer > numCount ;
33+
34+ /**
35+ * Initialize your data structure here.
36+ */
37+ public TwoSumIII () {
38+ this .numCount = new HashMap <>();
39+ }
40+
41+ /**
42+ * Add the number to an internal data structure..
43+ */
44+ public void add (int number ) {
45+ if (numCount .containsKey (number )) {
46+ numCount .put (number , 2 );
47+ } else {
48+ numCount .put (number , 1 );
49+ }
50+ }
51+
52+ /**
53+ * Find if there exists any pair of numbers which sum is equal to the value.
54+ */
55+ public boolean find (int value ) {
56+ for (Map .Entry <Integer , Integer > entry : numCount .entrySet ()) {
57+ int num1 = entry .getKey ();
58+ int num2 = value - num1 ;
59+ if ((num2 == num1 && entry .getValue () == 2 ) || (num1 != num2 && numCount .containsKey (num2 ))) {
60+ return true ;
61+ }
62+ }
63+ return false ;
64+ }
65+
66+ /**
67+ * Runtime: <a href="https://leetcode.com/submissions/detail/248632458/">115 ms</a>.
68+ *
69+ * @param args
70+ */
71+ public static void main (String [] args ) {
72+ TwoSumIII twoSumIII = new TwoSumIII ();
73+ twoSumIII .add (0 );
74+ twoSumIII .add (-1 );
75+ twoSumIII .add (1 );
76+ assertTrue (twoSumIII .find (0 ));
77+ }
78+ }
0 commit comments