方法1: 这道题目其实和two sum基本一样。这道题目难点就在于找到两个数的sum为一个给定的值。方法1我们用sorted list & two pointers来做。时间复杂nlogn,空间复杂n。具体思路参考lc官方解答1.
class TwoSum {
List<Integer> list = new ArrayList<>();
boolean is_sorted = false;
/** Initialize your data structure here. */
public TwoSum() {
}
/** Add the number to an internal data structure.. */
public void add(int number) {
list.add(number);
is_sorted = false;
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
if(!is_sorted){
Collections.sort(list);
}
int low = 0;
int high = list.size() - 1;
while(low < high){
int sum = list.get(low) + list.get(high);
if( sum == value) return true;
else if(sum > value) high--;
else low++;
}
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);
*/
方法2: hashtable。这也是解决two sum的一个好办法,不过时间复杂变为n,空间复杂n,空间复杂n。
class TwoSum {
Map<Integer, Integer> map = new HashMap<>();
/** Initialize your data structure here. */
public TwoSum() {
}
/** Add the number to an internal data structure.. */
public void add(int number) {
map.put(number, map.getOrDefault(number, 0) + 1);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for(int num : map.keySet()){
map.put(num, map.get(num) - 1);
int remain = value - num;
if(map.keySet().contains(remain) && map.get(remain) >= 1){
map.put(num, map.get(num) + 1);
return true;
}
map.put(num, map.get(num) + 1);
}
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);
*/
总结:
- 无