Design and implement a Twosum class. It should support the following operations: add and find .
-Add the number to an add internal data structure.
find-Find If there exists any pair of numbers which sum are equal to the value.
For example,
Add (1); Add (3); Add (5); Find (4)-Truefind (7)-False
Analysis:use O (1) Add and O (n) find. Solution:
Public classtwosum {HashMap<Integer,Integer> numcounts =NewHashmap<integer,integer>(); List<Integer> nums =NewArraylist<integer>(); //ADD the number to an internal data structure. Public voidAddintNumber ) { if(Numcounts.containskey (number)) {numcounts.put (number) {Number,numcounts.get (number)+1); } Else{nums.add (number); Numcounts.put (number,1); } } //Find If there exists any pair of numbers which sum are equal to the value. Public BooleanFindintvalue) { for(intnum:nums) { intOthernum = value-num; BooleanValidpair = (othernum==num)? (Numcounts.get (num) >=2): Numcounts.containskey (Othernum); if(Validpair) {return true; } } return false; }}//Your Twosum object would be instantiated and called as such://twosum twosum = new Twosum ();//Twosum.add (number);//Twosum.find (value);
Leetcode-two Sum iii-data Structure Design