【LeetCode】1. Two Sum 两数之和
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
- 个人公众号:负雪明烛
- 本文关键词:two sum, 两数之和,题解,leetcode, 力扣,Python, C++, Java
题目地址:https://leetcode.com/problems/two-sum/#/description
题目描述
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].
题目大意
找出两个索引,这两个索引对应的数组的数字之和等于target.
解题方法
字典+两次遍历
第一次遍历保存每个数字和索引的对应关系,第二次遍历nums找到target - num是不是在字典中,如果在的话还要保证同样的数字不能用两次。需要注意的是,如果有相同的数字在nums中出现,那么字典中只会保存后面的那个数字的位置,因此第二次遍历的时候一定只能从左到右的走。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i, num in enumerate(nums):
dic[num] = i
for i, num in enumerate(nums):
if target - num in dic and dic[target - num] != i:
return [i, dic[target - num]]
字典+一次遍历
这个遍历的方法其实就是只保存已经出现了的数字的方式。当遍历的过程中发现了目标在已经遍历过的字典中出现了,那么就停止,这样的题实在是太多了。
这个题首先想到的是时间复杂度O(n^2)的遍历,但是肯定会超时,所以想到用HashMap保存已经有的数据出现的位置,这样可以使如果要求的数字出现的时候不再继续遍历,及时停止即可。有个技巧就是判断差是否在HashMap中,而不是遍历一遍HashMap来求和。
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i])){
return new int[]{map.get(target - nums[i]), i};
}else{
map.put(nums[i], i);
}
}
return new int[2];
}
}
python解法如下,打败100%的提交。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
N = len(nums)
pos = dict()
for i, num in enumerate(nums):
if target - num in pos:
return [pos[target - num], i]
else:
pos[num] = i
return [0, 0]
双指针
另外有一个种解法是双指针解法,对nums进行排序,然后使用双指针分别从左边和右边向中间走,如果两者的和相加是target说明已经找到。再返回其在数组中的位置。
C++代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> copy = nums;
sort(nums.begin(), nums.end());
int left = 0;
int right = nums.size() - 1;
while (left != right) {
if (nums[left] + nums[right] == target)
break;
else if (nums[left] + nums[right] > target)
right --;
else
left ++;
}
vector<int> res(2, -1);
for (int i = 0; i < copy.size(); ++i) {
if (copy[i] == nums[left] && res[0] == -1) {
res[0] = i;
} else if (copy[i] == nums[right]) {
res[1] = i;
}
}
return res;
}
};
日期
2017 年 5 月 18 日
2018 年 11 月 22 日 —— 感恩节快乐~
【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:0002(两数之和)
LeetCode:0002(两数之和) 题目描述:给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表.你可以假设除了数字 0 之外,这两 ...
- Leetcode(1)两数之和
Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
随机推荐
- Perl if条件判断
Perl 条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 条件判断常用: True #布尔值 not True #布尔值 ! True ...
- 非标准的xml解析器的C++实现:三、解析器的初步实现
如同我之前的一篇文章说的那样,我没有支持DTD与命名空间, 当前实现出来的解析器,只能与xmlhttp对比,因为chrome浏览器解析大文档有bug,至于其他人实现的,我就不一一测试了,既然都决定自己 ...
- 使用dumi生成react组件库文档并发布到github pages
周末两天玩了下号称西湖区东半球最牛逼的react文档站点生成工具dumi,顺带结合github pages生成了react-uni-comps文档站, 一套弄下来,感觉真香,现在还只是浅尝,高级的特性 ...
- 学习java的第十六天
一.今日收获 1.完成了手册第二章没有验证完成的例题 2.预习了第三章的算法以及for语句与if语句的用法 二.今日难题 1.验证上出现问题,没有那么仔细. 2.第二章还有没有完全理解的问题 三.明日 ...
- day01 MySQL发展史
day01 MySQL发展史 今日内容概要 数据库演变史 软件开发架构 数据库本质 数据库中的重要概念 MySQL下载与安装 基本SQL语句 今日内容详细 数据库演变史 # 1.文件操作阶段 jaso ...
- Spark(十二)【SparkSql中数据读取和保存】
一. 读取和保存说明 SparkSQL提供了通用的保存数据和数据加载的方式,还提供了专用的方式 读取:通用和专用 保存 保存有四种模式: 默认: error : 输出目录存在就报错 append: 向 ...
- my36_InnoDB关键特性之change buffer
一.关于IOT:索引组织表 表在存储的时候按照主键排序进行存储,同时在主键上建立一棵树,这样就形成了一个索引组织表,一个表的存储方式以索引的方式来组织存储的. 所以,MySQL表一定要加上主键,通过主 ...
- linux 磁盘满了,vim 编辑文件时无法保存
早上来发现 redis 不能用,报 MISCONF Redis is configured to save RDB snapshots, but it is currently not able to ...
- js - 日期、时间 Date对象方法
Date 是 JS 内置的日期构造函数 var d = new Date(); // 这个是系统当前时间的日期实例 d.getYear(); // 返回 d 实例年份 - 1900 d.getFul ...
- 【Office】【Excel】将多个工作薄合为一个工作薄
前提:工作薄首行不能有合并的单元格 准备工作:将要合并的工作簿放在一个文件夹里面,文件夹中不能有乱七八糟的东西,只能有你要合并的工作薄 操作步骤:在此文件夹下创建Excel表格并打开,按下alt+F1 ...