設計并實現一個?TwoSum 的類,使該類需要支持 add?和?find?的操作。
add?操作 -??對內部數據結構增加一個數。
find 操作 - 尋找內部數據結構中是否存在一對整數,使得兩數之和與給定的數相等。
示例?1:
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
示例?2:
add(3); add(1); add(2);
find(3) -> true
find(6) -> false
在列表有序的情況下,可以使用雙指針,時間為O(N),插入一個數字的時間為O(N)。
可以使用哈希表,查找的時間為O(N),插入時間為O(1)。
兩種方法空間都是O(N)。
綜上所述,沒有排序的列表沒有必要為了解題去排序。
設計此數據結構時,也是使用哈希表最好。
import java.util.HashMap;class TwoSum {private HashMap<Integer, Integer> countsMap;/** Initialize your data structure here. */public TwoSum() {countsMap = new HashMap<Integer, Integer>();}/** Add the number to an internal data structure.. */public void add(int number) {if (countsMap.containsKey(number))countsMap.replace(number, countsMap.get(number) + 1);elsecountsMap.put(number, 1);}/** Find if there exists any pair of numbers which sum is equal to the value. */public boolean find(int value) {for (Map.Entry<Integer, Integer> entry : countsMap.entrySet()) {int key = value - entry.getKey();if ((key == entry.getKey() && entry.getValue() > 1)|| (key != entry.getKey() && countsMap.containsKey(key))) {return true;}}return false;}
}/*** Your TwoSum object will be instantiated and called as such:* TwoSum obj = new TwoSum();* obj.add(number);* boolean param_2 = obj.find(value);*/
?