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【41】利用不等式妙消参数

    已知$\theta\in[0,2\pi]$对任意$x\in[0,1],2x^2sin\theta-4x(1-x)cos\theta+3(1-x)^2>0$恒成立.求$\theta$的范围. 解答 ...

  2. 自学Zabbix4.2 web监控项创建+item详解

    自学Zabbix4.2 web监控项创建+item详解 1. web监控项创建 1.1  Scenario 选项卡 Name: 监控项的名称 Application: 放到哪个应用中 Authenti ...

  3. [hgoi#2019/2/24]玄学考试

    感想 对于这次考试,真的不想说什么了,太玄学了!!! t1输出比标准输出长,这是什么操作???难道要关文件???但是交到oj上又A掉了.这是什么操作. t2还好,没有出什么意外...但是要吐槽一下出题 ...

  4. Java -- JDBC 学习--PreparedStatement

    可以通过调用 Connection 对象的 preparedStatement() 方法获取 PreparedStatement 对象.PreparedStatement 接口是 Statement ...

  5. Linux下的定时器类实现(select定时+线程)

    更好的计时器类实现:LINUX RTC机制实现计时器类(原创) 很多时候需要在LINUX下用到定时器,但像setitimer()和alarm()这样的定时器有时会和sleep()函数发生冲突,这样就给 ...

  6. jQuery倒计时代码(超简单)

    <!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8&q ...

  7. A*算法(附c源码)

    关于A*算法网上介绍的有很多,我只是看了之后对这个算法用c写了一下,并测试无误后上传以分享一下,欢迎指正!下面是我找的一个介绍,并主要根据这个实现的. 寻路算法不止 A* 这一种, 还有递归, 非递归 ...

  8. call_user_func 和 call_user_func_array用法

    说明 call_user_func 和 call_user_func_array 相同:都可以调用函数和类内部的函数,不同:不同的是传递的参数不同,前者是一个参数一个参数传递, 后者是传递array参 ...

  9. linux系统--磁盘管理命令(二)

    一.硬盘的分区模式 之前的硬盘分区模式为MBR 主分区不超过4个 单个分区容量最大为2TB 前面的分区模式就为MBR分区模式. 另一种分区模式为GPT 主分区个数限制:在GPT的分区表中最多可以支持1 ...

  10. 法律AI数据及应用

    本文简单列举了法律AI目前的应用,数据集,研究方向. 历史 1970年,Buchanan和Headrick发表文章"关于人工智能和法律推理的一些猜测",讨论了对法律研究和推理进行建 ...