您的位置:首页 > 其它

170. Two Sum III - Data structure design

2017-01-23 07:51 375 查看
Design and implement a TwoSum class. It should support the following operations: 
add
 and 
find
.

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


add快

public class TwoSum {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
/** Initialize your data structure here. */
public TwoSum() {

}

/** Add the number to an internal data structure.. */
public void add(int number) {
if(map.containsKey(number)){
map.put(number, map.get(number) + 1);
}else{
map.put(number, 1);
}
}

/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for(Integer i : map.keySet()){
int number = value - i;
if(map.containsKey(number)){
if(number == i && map.get(i) < 2){ //避免返回自己。add(0), find(0),这时候应该返回FALSE,因为没有这种pair.
continue;//但是如果用set的话就会返回true
}else{
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);
*/

search快

public class TwoSum {
Set<Integer> sum;
Set<Integer> num;

TwoSum(){
sum = new HashSet<Integer>();
num = new HashSet<Integer>();
}
// Add the number to an internal data structure.
public void add(int number) {
if(num.contains(number)){
sum.add(number * 2);
}else{
Iterator<Integer> iter = num.iterator();
while(iter.hasNext()){
sum.add(iter.next() + number);
}
num.add(number);
}
}

// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
return sum.contains(value);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: