https://leetcode.com/problems/two-sum-iii-data-structure-design/description/
Time Limit Exceeded:
class TwoSum {
private LinkedList<Integer> list;
private HashSet<Integer> set;
/** Initialize your data structure here. */
public TwoSum() {
list = new LinkedList<>();
set = new HashSet<>();
}
/** Add the number to an internal data structure.. */
public void add(int number) {
for (int item: list) {
set.add(item + number);
}
list.add(number);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
return set.contains(value);
}
}
passed: LinkedList + HashMap
这种解法有两个好处:
- 易于重复性很多的数值
- Extension: 如果需要进行删除操作, 这种写法更容易。
个人更喜欢上面 HashSet 的解法,find 操作 O(1)。看哪个操作使用的更频繁了。
class TwoSum {
private LinkedList<Integer> list; // uniq number
private HashMap<Integer, Integer> map; // item and its count
/** Initialize your data structure here. */
public TwoSum() {
list = new LinkedList<>();
map = new HashMap<>();
}
/** Add the number to an internal data structure.. */
public void add(int num) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
list.add(num);
}
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find(int value) {
for (Integer num1: list) {
int num2 = value - num1;
if ((num1 == num2 && map.get(num1) >= 2) || (num1 != num2) && map.containsKey(num2)) {
return true;
}
}
return false;
}
}
网友评论