篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 170.两个Sum III - 数据结构design.java相关的知识,希望对你有一定的参考价值。
public class TwoSum {
private HashMap<Integer, Integer> dict; // using map instead of set is because allowing repetition
private List<Integer> nums;
/** Initialize your data structure here. */
public TwoSum() {
dict = new HashMap<Integer, Integer>();
nums = new ArrayList<Integer>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
if(dict.containsKey(number)){
dict.put(number, dict.get(number) + 1);
} else {
nums.add(number);
dict.put(number, 1);
}
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for(int i=0; i < nums.size(); i++){
int num1 = nums.get(i);
int num2 = value - num1;
if(num1 == num2 && dict.get(num1) > 1) return true;
if(num1 != num2 && dict.containsKey(num2)) 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);
*/
以上是关于java 170.两个Sum III - 数据结构design.java的主要内容,如果未能解决你的问题,请参考以下文章