[LeetCode] 1. Two Sum 两数和
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给一个没排序的包含整数的数组,找出使得两个数的和是给定值的indices。假设每个输入只有一个答案, 同一元素不会用到两次。
解法:
1. 暴力解法,两个for循环遍历,两个数相加和目标数比较。Time: O(n^2)
2. 先对数组快速排序,然后用两个指针分别指向头和尾,每次比较头尾两个数的和,如果比target小,头标记右移,如果大,尾标记左移。需要注意记录快速排序前后数字的位置变化。Time: O(n)
3. 先遍历一遍数组,建立数字和index的HashMap,然后再遍历一遍,开始查找target - num[i]是否在map中,如果在,找到并返回index。Time: O(n) Space: O(n)
Java:解法1
public static int[] twoSum(int[] numbers, int target) {
int[] ret = new int[2];
for (int i = 0; i < numbers.length; i++) {
for (int j = i + 1; j < numbers.length; j++) {
if (numbers[i] + numbers[j] == target) {
ret[0] = i + 1;
ret[1] = j + 1;
}
}
}
return ret;
}
Java:解法2
class Pair implements Comparable<Pair>{
public int number;
public int idx;
public Pair(int number, int idx){
this.number = number;
this.idx = idx;
}
public int compareTo(Pair other){
return this.number - other.number;
}
}
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int n = numbers.length;
Pair[] pairs = new Pair[n];
for(int i = 0; i < n; ++i){
pairs[i] = new Pair(numbers[i], i + 1);
}
Arrays.sort(pairs);
int [] result = new int[2];
int begin = 0;
int end = n - 1;
while(begin < end){
if(pairs[begin].number + pairs[end].number < target){
begin++;
}
else if (pairs[begin].number + pairs[end].number > target){
end--;
}
else{
if(pairs[begin].idx > pairs[end].idx){
result[0] = pairs[end].idx;
result[1] = pairs[begin].idx;
}else{
result[0] = pairs[begin].idx;
result[1] = pairs[end].idx;
}
break;
}
}
return result;
}
}
Java: 解法3,Two loops
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
m.put(nums[i], i);
}
for (int i = 0; i < nums.length; ++i) {
int t = target - nums[i];
if (m.containsKey(t) && m.get(t) != i) {
res[0] = i;
res[1] = m.get(t);
break;
}
}
return res;
}
}
Java: 解法3,one loop
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
if (m.containsKey(target - nums[i])) {
res[0] = i;
res[1] = m.get(target - nums[i]);
break;
}
m.put(nums[i], i);
}
return res;
}
}
Python:
class Solution(object):
def twoSum(self, nums, target):
hash_map = {}
for i, v in enumerate(nums):
hash_map[v] = i for index1, value in enumerate(nums):
if target - value in hash_map:
index2 = hash_map[target - value]
if index1 != index2:
return [index1, index2]
Python:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num], i]
lookup[num] = i
Python: wo
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i in range(len(nums)):
if target - nums[i] in lookup:
return [lookup[target - nums[i]], i]
lookup[nums[i]] = i
Python:
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> lookup;
for (int i = 0; i < nums.size(); ++i) {
if (lookup.count(target - nums[i])) {
return {lookup[target - nums[i]], i};
}
lookup[nums[i]] = i;
}
return {};
}
};
相似题目:
[LeetCode] 167. Two Sum II - Input array is sorted 两数和 II - 输入是有序的数组
[LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计
[LeetCode] 653. Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
All LeetCode Questions List 题目汇总
[LeetCode] 1. Two Sum 两数和的更多相关文章
- [LeetCode] 1. Two Sum 两数之和
Part 1. 题目描述 (easy) Given an array of integers, return indices of the two numbers such that they add ...
- [LeetCode]1.Two Sum 两数之和&&第一次刷题感想
---恢复内容开始--- 参考博客: https://www.cnblogs.com/grandyang/p/4130379.html https://blog.csdn.net/weixin_387 ...
- [LeetCode] 1.Two Sum 两数之和分析以及实现 (golang)
题目描述: /* Given an array of integers, return indices of the two numbers such that they add up to a sp ...
- 【LeetCode】Two Sum(两数之和)
这道题是LeetCode里的第1道题. 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会 ...
- [leetcode]1. Two Sum两数之和
Given an array of integers, return indices of the two numbers such that they add up to a specific t ...
- [LeetCode]1.Two Sum 两数之和(Java)
原题地址:two-sum 题目描述: 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标. 你可以假设每 ...
- LeetCode刷题 1. Two Sum 两数之和 详解 C++语言实现 java语言实现
1. Two Sum 两数之和 Given an array of integers, return indices of the two numbers such that they add up ...
- 【LeetCode】1. Two Sum 两数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:two sum, 两数之和,题解,leetcode, 力 ...
- Leetcode:0002(两数之和)
LeetCode:0002(两数之和) 题目描述:给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表.你可以假设除了数字 0 之外,这两 ...
随机推荐
- CentOS6.5_x64上简单编译配置Heartbeat3.0.4
Heartbeat 3与 2.x的最大差别在于,3 按模块把的原来2.x 拆分为多个子项目,并且提供了一个cluster-glue的组件,专用于Local ResourceManager 的管理.即h ...
- Alpha冲刺(10/10)——2019.5.3
所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(10/10)--2019.5.3 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...
- mybatis框架-SqlSession会话操作数据库的两种方式
1.通过SqlSession实力来直接执行已经映射的sql语句 例如,查询整个用户表中的信息 在UserMapper.xml中编写sql语句 编写测试方法: 注意:这里使用的selectList方法: ...
- LeetCode 818. Race Car
原题链接在这里:https://leetcode.com/problems/race-car/ 题目: Your car starts at position 0 and speed +1 on an ...
- 洛谷 P1226 【模板】快速幂||取余运算 题解
Analysis 快速幂模板,注意在最后输出时也要取模. 快速幂模板 inline ll ksm(ll x,ll y) { ll ans=; ) { ) { ans*=x; ans%=k; } x*= ...
- 开源项目 11 Ionic Zip
using Ionic.Zip; using System; using System.Collections.Generic; using System.IO; using System.Linq; ...
- 洛谷 P2004 领地选择 题解
P2004 领地选择 题目描述 作为在虚拟世界里统帅千军万马的领袖,小Z认为天时.地利.人和三者是缺一不可的,所以,谨慎地选择首都的位置对于小T来说是非常重要的. 首都被认为是一个占地C*C的正方形. ...
- Web前端开发工具和环境清单
初级 浏览器 Google Chrome 75.0.3770.100www.google.cn/intl/zh-CN/chrome初级 移动端模拟器 Genymotion 6.0.6www.genym ...
- CDH CM版本 6.0.1 升级到 CM 6.2.0 当前最新版本(CentOS 7.x)
CDH 的 6.0.1 是一个尴尬的版本,那时候 cloudera 还没有将 spark 更新到 2.4 还使用的是 spark 2.2版本. 但后来我们发现 2.3 | 2.4 更新了非常多的 fe ...
- 菜鸟学IT之豆瓣爬取初体验
作业来源:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3159 可以用pandas读出之前保存的数据: newsdf = pd.re ...