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 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 & III & IV的更多相关文章
- combination sum(I, II, III, IV)
II 简单dfs vector<vector<int>> combinationSum2(vector<int>& candidates, int targ ...
- 买卖股票的最佳时机I II III IV
I 假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格.如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润. II 假设有一个数组,它的第i个元素是一个给定的股票 ...
- 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 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(II和IV)
本文包含leetcode上的Two Sum(Python实现).Two Sum II - Input array is sorted(Python实现).Two Sum IV - Input is a ...
- 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 ...
- hdu 3081 hdu 3277 hdu 3416 Marriage Match II III IV //灵活运用最大流量
3081 意甲冠军: n女生选择不吵架,他甚至男孩边(他的朋友也算.并为您收集过程).2二分图,一些副作用,有几个追求完美搭配(每场比赛没有重复的每一个点的比赛) 后.每次增广一单位,(一次完美匹配) ...
- 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 ...
随机推荐
- android 面试准备基础题
1. 请描述下Activity的生命周期. 必调用的三个方法:onCreate() --> onStart() --> onResume(),用AAA表示 )父Activity启动子 ...
- [luogu3258][JLOI2014]松鼠的新家
题解 我们就在\([a_i,a_{i+1}]\)的路径上都\(+1\),然后单点查询就可以了. ac代码(吸了氧才过的QwQ) # include <bits/stdc++.h> # de ...
- 洛谷 P1462 通往奥格瑞玛的道路 解题报告
P1462 通往奥格瑞玛的道路 题目背景 在艾泽拉斯大陆上有一位名叫歪嘴哦的神奇术士,他是部落的中坚力量 有一天他醒来后发现自己居然到了联盟的主城暴风城 在被众多联盟的士兵攻击后,他决定逃回自己的家乡 ...
- 01---JMS与消息中间件的基本概念
JMS消息服务介绍和使用场景 什么是JMS JMS : Java Message Service(Java消息服务),Java平台中关于面向消息中间件的接口. 重点在于接口,接口就意味着与JDBC类似 ...
- Mysql服务器处理客户端请求流程
在日常执行mysql语句的过程中,都是客户端进程向服务器进程发送一段文本(MySQL语句),服务器进程处理后再向客户端进程发送一段文本(处理结果). 看似很简单,其实不然,这内容有很多东西是需要注意的 ...
- CF848E Days of Floral Colours——DP+多项式求逆/分治NTT
官方题解:http://codeforces.com/blog/entry/54233 就是由简入繁 1.序列处理,只考虑一个半圆 2.环形处理(其实这个就是多了旋转同构) 然后基于分割线邻居的跨越与 ...
- 【洛谷P1717】钓鱼
题目大意:给定 N 个位置,每个位置有一个答案贡献值,在一个位置加了一次该位置的答案贡献值之后,该值会减掉一部分,从一个位置移动到另一个位置需要花费一定的时间,问:给定 M 单位的时间,如何移动使得答 ...
- [luogu1327][生活大爆炸石头剪子布]
题目地址 https://www.luogu.org/problemnew/show/P1328 题目描述 石头剪刀布是常见的猜拳游戏:石头胜剪刀,剪刀胜布,布胜石头.如果两个人出拳一样,则不分胜负. ...
- Sublime Text3—Project(项目管理)
摘要 Project 可以理解为项目.工程或者站点,以下称项目.使用项目管理的好处是:不用将所有文件都放到同一个根目录,可以将相关但不同路径的文件组成一个Project,每个项目都是独立的,文件的状态 ...
- Log4j 2X 日志文件路径问题
关于路径问题网上说啥的都有,但是也不能说人家错,只能说不适合你这个. 一开始,我用的 ${webapp.root} <RollingFile name="rollingFileSy ...