[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 之外,这两 ...
随机推荐
- app开发-3
一.Audio 模块实现开启手机摄像头 基于html5 plus http://www.html5plus.org/doc/zh_cn/audio.html 栗子: 自定义: scanQR.HTM ...
- js实现文本框自动显示两位小数
转自https://blog.csdn.net/qiji2011/article/details/81270552 1.js: //保留2位小数,如:2,会在2后面补上00.即2.00 functio ...
- CentOS6.5配置
关闭防火墙 查看防火墙状态 /etc/init.d/iptables status 停止 /etc/init.d/iptables stop 开机不启动 chkconfig iptables off ...
- PHP程序员最容易犯的Mysql错误
对于大多数web应用来说,数据库都是一个十分基础性的部分.如果你在使用PHP,那么你很可能也在使用MySQL—LAMP系列中举足轻重的一份子. 对于很多新手们来说,使用PHP可以在短短几个小时之内轻松 ...
- Array.Sort(valuesArry);
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
- 使用Quasar设计Material和IOS风格的响应式网站
使用Quasar设计Material和IOS风格的响应式网站 栏目: CSS · 发布时间: 8个月前 来源: segmentfault.com 本文转载自:https://segmentfaul ...
- MySQL 已有大数据量表进行分区踩坑
一.背景mysql 表中已有 4 亿数据,为提高查询效率,需创建分区,一开始计划是创建 HASH 分区,结果报错:ERROR 1659 (HY000): Field 'partno' is of a ...
- 用OKR提升员工的执行力
很多管理者在公司管控的过程中常常出现一种乏力的感觉,觉得很多事情推进不下去,结果总是令人不满意.管理者总是会吐槽,“员工执行力差!”而此时大部分管理者会认为公司执行力差是员工能力和态度的问题. 事实上 ...
- Github搭建简单的博客
1)安装pelcan和markdown pip install pelican markdown --upgrade 2)创建一个文件夹用来作为博客的目录 mkdir 博客目录 3)cd到该目录下运行 ...
- zabbix-trap
安装 yum -y install zabbix-sender zabbix sender 在客户端给server端发送信息, -z 指定server的ip -p 指定端口 10051 -s 被监控设 ...