Two Sum I & II
Two Sum I
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum
should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
You may assume that each input would have exactly one solution
numbers=[2, 7, 11, 15]
, target=9
return [0, 1]
分析:
利用hashMap把值和对应的Index放在里面。然后对于剩余的值,在hashmap里查找就可以了。
class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[];
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = ; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[] = map.get(target - numbers[i]);
result[] = i;
return result;
}
map.put(numbers[i], i);
}
return result;
}
}
扩展:如果里面不止一对,需要找出所有的,并且数组中的数还可能有重复,这种情况也是同样的处理方法,只是把map中的值变成ArrayList就可以了。
Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
- Your returned answers (both index1 and index2) are not zero-based.
- You may assume that each input would have exactly one solution and you may not use the sameelement twice.
class Solution {
public int[] twoSum(int[] numbers, int target) {
if (numbers == null || numbers.length == ) {
return null;
}
int i = ;
int j = numbers.length - ; while (i < j) {
int sum = numbers[i] + numbers[j];
if (sum < target) {
++i;
} else if (sum > target) {
j--;
} else {
return new int[] { i + , j + };
}
}
return null;
}
}
Two Sum III
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
public class TwoSum {
HashMap<Integer, Integer> map; public TwoSum() {
map = new HashMap<Integer, Integer>();
} public void add(int x) {
map.put(x, map.getOrDefault(x, ) + );
} public boolean find(int target) {
for (int i : map.keySet()) {
if (map.containsKey(target - i)) {
if (target - i != i || map.get(i) >= )
return true;
}
}
return false;
}
}
If find method is called very frequently, we should use the implementation below.
public class TwoSum {
private Set<Integer> sum, num; public 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 * );
} 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);
}
}
Two Sum IV - Input is a BST
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7 Target = 9 Output: True
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7 Target = 28 Output: False
方法一:先把bst转化成一个sorted arraylist, 然后用上一题的方法即可。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
if (root == null) {
return false;
}
List<Integer> list = new ArrayList();
inorder(root, list);
int i = ;
int j = list.size() - ; while (j > i) {
long sum = list.get(i) + list.get(j);
if (sum == k) {
return true;
} else if (sum > k) {
j--;
} else {
i++;
}
}
return false;
} private void inorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
}
}
方法二:利用递归+ hashset. 这个方法有点意思,所以记录下来。
class Solution {
public boolean findTarget(TreeNode root, int k) {
if (root == null) {
return false;
}
Set<Integer> numbers = new HashSet();
return dfs(root, numbers, k);
} private boolean dfs(TreeNode root, Set<Integer> numbers, int k) {
if (root == null) {
return false;
} if (numbers.contains(k - root.val)) {
return true;
}
numbers.add(root.val);
return dfs(root.left, numbers, k) || dfs(root.right, numbers, k);
}
}
Two Sum I & II的更多相关文章
- 1. Two Sum I & II & III
1. Given an array of integers, return indices of the two numbers such that they add up to a specific ...
- [Leetcode][JAVA] Path Sum I && II
Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addi ...
- LeetCode:Combination Sum I II
Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...
- LeetCode:Path Sum I II
LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...
- Nested List Weight Sum I & II
Nested List Weight Sum I Given a nested list of integers, return the sum of all integers in the list ...
- Leetcode 39 40 216 Combination Sum I II III
Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combin ...
- Path Sum I && II & III
Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that ad ...
- Two Sum I & II & III & IV
Two Sum I Given an array of integers, find two numbers such that they add up to a specific target nu ...
- Interval Sum I && II
Given an integer array (index from 0 to n-1, where n is the size of this array), and an query list. ...
随机推荐
- TRUNC函数,ORA-01898 精度说明符过多
TRUNC(SYSDATE)即可默认当前日期(年月日),TRUNC(SYSDATE,'yyyy-mm-dd'),精度说明符过多
- hdu2072 字典树
这题印象深刻,我刚接触acm时,以为这题是水题(因为是中文,又短),一直没做出.现再想想也是.可能也是我以前字符串掌握不好: 这题其实也可以用stl里的map写.这里我用字典树写的.其实这题算简单题了 ...
- Maven-改变本地存储仓库位置
修改 maven 仓库存放位置: 找到 maven 下的 conf 下的 settings.xml 配置文件,假设maven安装在D:\Server目录中.那么配置文件应该在 D:\Server\ma ...
- Java-Vector
package 集合类.list类; import java.util.Vector; public class Vector类 { public static void main(String[] ...
- NS图绘制工具推荐
世界上要画NS图的人肯定很少,这种无聊的东西= = 我根据个人经验和直觉,推荐三个套工具. 一.签字笔(铅笔+橡皮)+作业纸+拍照的手机 鉴于我以前手绘版ns图已经找不到了,就用室友之前画的做个例子. ...
- 【poj1010】 STAMPS
http://poj.org/problem?id=1010 (题目链接) 感到了英语深深的恶意... 题意(真的很难懂....) 第一行数字是邮票的面值,每一个数字就是一个不同的种类,哪怕面值相同. ...
- HDU 1060 Left-most Digit
传送门 Leftmost Digit Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Other ...
- POJ2049Finding Nemo(bfs + 构图)
Finding Nemo Time Limit: 2000MS Memory Limit: 30000K Total Submissions: 8456 Accepted: 1975 Desc ...
- classpath、path、JAVA_HOME的作用
CLASSPATH是什么?它的作用是什么? 它是javac编译器的一个环境变量. 它的作用与import.package关键字有关. 当你写下improt java.util.*时,编译器面对impo ...
- 菲涅尔反射(Fresnel Reflection)
离线渲染中,通常可以用kd,ks,kt(分别代表物体的漫反射系数,镜面反射系数,透射系数)来简单地描述一个物体的基本材质,例如,我们将一个物体设置为:kd=0,ks=0.1,kt=0.9,即代表一束光 ...