您的位置:首页 > 其它

Two Sum III - Data structure design

2016-06-08 06:14 330 查看
丢人!!!即便我们是在公司偷闲。。。。。。

是否要处理重复数字?如何处理?????

怎么写的这么痛苦

public class TwoSum {

private Map<Integer/*value*/, Integer/*number*/> map = new HashMap<>();
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 (int valueKey: map.keySet()) {
int target = value - valueKey;
if (target == valueKey && map.get(target) > 1) {
return true;
} else if (target != valueKey && map.containsKey(target)) {
return true;
}
}
return false;
}

// // Add the number to an internal data structure.
// public void add(int number) {
// //list.add(number);
// set.add(number);
// }
//
// // Find if there exists any pair of numbers which sum is equal to the value.
// public boolean find(int value) {
// Iterator<Integer> i = set.iterator();
// while (i.hasNext()) {
// int s = i.next();
// if (set.contains(value - s)) {
// if (set.contains(s))
// return false;
// return true;
// }
// }
// //Set<Integer/*Value*/> set = new HashSet<>();
//// for (int i = 0; i < list.size(); i++) {
//// if (set.contains(list.get(i))) {
//// return true;
//// } else {
//// set.add(value - list.get(i));
//// }
//// }
// return false;
// }
//
// //private List<Integer> list = null;
// private Set<Integer> set = null;
//
// public TwoSum() {
// //list = new LinkedList<>();
// set = new HashSet<>();
// }

}

// Your TwoSum object will be instantiated and called as such:
// TwoSum twoSum = new TwoSum();
// twoSum.add(number);
// twoSum.find(value);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: