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

Example

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 & III & IV的更多相关文章

  1. combination sum(I, II, III, IV)

    II 简单dfs vector<vector<int>> combinationSum2(vector<int>& candidates, int targ ...

  2. 买卖股票的最佳时机I II III IV

    I 假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格.如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润. II 假设有一个数组,它的第i个元素是一个给定的股票 ...

  3. 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 ...

  4. 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 ...

  5. 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 ...

  6. Two Sum(II和IV)

    本文包含leetcode上的Two Sum(Python实现).Two Sum II - Input array is sorted(Python实现).Two Sum IV - Input is a ...

  7. Best Time to Buy and Sell Stock I II III IV

    一.Best Time to Buy and Sell Stock I Say you have an array for which the ith element is the price of ...

  8. hdu 3081 hdu 3277 hdu 3416 Marriage Match II III IV //灵活运用最大流量

    3081 意甲冠军: n女生选择不吵架,他甚至男孩边(他的朋友也算.并为您收集过程).2二分图,一些副作用,有几个追求完美搭配(每场比赛没有重复的每一个点的比赛) 后.每次增广一单位,(一次完美匹配) ...

  9. LeetCode之“动态规划”:Best Time to Buy and Sell Stock I && II && III && IV

    Best Time to Buy and Sell Stock I 题目链接 题目要求: Say you have an array for which the ith element is the ...

随机推荐

  1. MT【24】一道五次方程的求根题

    解答: 评:一般的五次及以上的多项式方程是无根式解的,只能用计算机去精确到某某位.但是特殊的比如$x^5=1$显然有根式解,本题就是一个不平凡的特殊的例子,这里的代换用于求解三次方程的求根过程是一样的 ...

  2. [TJOI2011]构造矩阵

    考虑优化贪心,不回溯,对于每一位,你都判一下放0的话后面是否有解,用网络流判是否可以完美匹配就行了. 但这样时间复杂是错的,所以不必每次都重新建图,现在原来的图中看一下该行列是否已经匹配,若没有,则强 ...

  3. 10 Zabbix Item类型之Zabbix IPMI类型

    点击返回:自学Zabbix之路 Zabbix Item类型之Zabbix IPMI类型 一般使用zabbix IPMI 监控硬件信息,比如说温度. 在编译安装zabbix server的时候,一定要加 ...

  4. 自学Aruba7.1-Aruba安全认证-WPA2-PSK认证(web页面配置)

    点击返回:自学Aruba之路 自学Aruba7.1-Aruba安全认证-WPA2-PSK认证(web页面配置) 步骤1 建立AP Group,命名为test-group 步骤2  将AP加入到AP G ...

  5. 自学Zabbix11.5 Zabbix SNMP监控实例

    点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 自学Zabbix11.5 Zabbix SNMP监控实例-监控网络设备内存使用情况 1. zabb ...

  6. Android在初始化时弹出popwindow的方法

     http://blog.csdn.net/sxsboat/article/details/7340759 Android中在onCreate()时弹出popwindow,很多人都有过类似的需求吧,但 ...

  7. 【POJ3694】Network

    题目大意:给定一个 N 个点,M 条边的无向图,支持 Q 次操作,每次可以向该无向图中加入一条边,并需要回答当前无向图中桥的个数. 题解:(暴力:Q 次 Tarjan) 先进行一次 Tarjan 求出 ...

  8. 【模板】倍增+Floyd

    题目大意:给定一个 N 个顶点的邻接矩阵.起点顶点.终点顶点,求至少经过 K 条边(边可以重复)从起点到终点的最短路长度,若不能到达,输出 -1. 题解:至少经过 K 条边和恰好经过 K 条边的初始条 ...

  9. [codevs3342][绿色通道]

    codevs3342 思路: 既然是要求最小化最长空题段,直接二分答案.然后就是check函数的写法. 先考虑n方转移,假设当前二分的答案是x,用f[i]表示前i个题,第i道题写的最小花费时间.最后再 ...

  10. Windows7 64下搭建Caffe+python接口环境

    参考链接: http://www.cnblogs.com/yixuan-xu/p/5858595.html http://www.cnblogs.com/zf-blog/p/6139044.html ...