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.
Example
add(1); add(3); add(5);
find(4) // return true
find(7) // return false
使用两种方法
(1)使用list的方法,每次计算find的时候,需要重新运行
(2)使用hashmap的方式进行加速
java1
public class TwoSum {
/*
* @param number: An integer
* @return: nothing
*/
List<Integer> list = new ArrayList<>();
public void add(int number) {
// write your code here
list.add(number);
}
/*
* @param value: An integer
* @return: Find if there exists any pair of numbers which sum is equal to the value.
*/
public boolean find(int value) {
// write your code here
int left = 0;
int right = list.size() - 1;
int sum = 0;
Collections.sort(list);
while (left < right) {
sum = list.get(left) + list.get(right);
if (sum == value) {
return true;
} else if (sum > value) {
right--;
} else {
left++;
}
}
return false;
}
}
java2
public class TwoSum {
/*
* @param number: An integer
* @return: nothing
*/
List<Integer> list = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
public void add(int number) {
// write your code here
if (map.containsKey(number)) {
map.put(number, map.get(number) + 1);
} else {
list.add(number);
map.put(number, 1);
}
}
/*
* @param value: An integer
* @return: Find if there exists any pair of numbers which sum is equal to the value.
*/
public boolean find(int value) {
// write your code here
for (int i = 0; i < list.size(); i++) {
int num = list.get(i);
int target = value - num;
if (num == target && map.get(num) > 1) {
return true;
} else if (num != target && map.containsKey(target)) {
return true;
}
}
return false;
}
}