Design and implement a TwoSum class. It should support the following operations:addandfind.
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
呵呵呵奇葩了, 這個也是各種不過, 想找個完美解決方案,就去看討論區別人的代碼, 怎么都不滿意, 突然發現一個我想要的代碼, 心里一陣竊喜, 結果你猜這么著。那個代碼發布者是我自己?。。?!尼瑪??!摔鍵盤, 砸鼠標!
? ? ?HashMap<Integer, Integer> map = new HashMap<>();?
? ? ? public void add(int number) {
? ? ? ? ? ? map.put(number, map.getOrDefault(number,0) + 1);
? ? ? }?
? ? ? public boolean find(int value) {
? ? ? ? ? ? Set<Integer> keyset = map.keySet();
? ? ? ? ? ? for(Integer key: keyset){
? ? ? ? ? ? ? ? ? ?if(value == key * 2 && map.get(key) > 1
? ? ? ? ? ? ? ? ? ? ? || value != key * 2 && map.containsKey(value - key) ){
? ? ? ? ? ? ? ? ? ? ? ? ? ? return true;
? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?}
? ? ? ? ? ? return false;
? ? ?}