【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,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
随机推荐
- python-django-请求响应对象
用户请求终端的信息: 包括使用的ip地址,浏览器类型等 cookie: 测试测试: def print_request(request): print(request) print("!!! ...
- vector去重--unique
具体实现见中间源码 function template <algorithm> std::unique equality (1) template <class ForwardIte ...
- Demo02一千以内的水仙花数
package 习题集2;//1000以内的水仙花数public class Demo02 { public static void main(String[] args) { int i = 100 ...
- day02 Rsyuc备份服务器
day02 Rsyuc备份服务器 一.备份 1.什么是备份 备份就是把重要的数据或者文件复制一份保存到另一个地方,实现不同主机之间的数据同步 一般数据比较重要的情况下,数据如果丢失很容易找不回来了的, ...
- 大数据学习day32-----spark12-----1. sparkstreaming(1.1简介,1.2 sparkstreaming入门程序(统计单词个数,updateStageByKey的用法,1.3 SparkStreaming整合Kafka,1.4 SparkStreaming获取KafkaRDD的偏移量,并将偏移量写入kafka中)
1. Spark Streaming 1.1 简介(来源:spark官网介绍) Spark Streaming是Spark Core API的扩展,其是支持可伸缩.高吞吐量.容错的实时数据流处理.Sp ...
- 大数据学习day29-----spark09-------1. 练习: 统计店铺按月份的销售额和累计到该月的总销售额(SQL, DSL,RDD) 2. 分组topN的实现(row_number(), rank(), dense_rank()方法的区别)3. spark自定义函数-UDF
1. 练习 数据: (1)需求1:统计有过连续3天以上销售的店铺有哪些,并且计算出连续三天以上的销售额 第一步:将每天的金额求和(同一天可能会有多个订单) SELECT sid,dt,SUM(mone ...
- webpack打包报错 ERROR in ./js/ww.js from UglifyJs Unexpected token keyword «function», expected punc «,» [src/page/ww/view/xx/xx.vue:119,0][./js/ww.js:55218,17]
找了好多解决办法 你可以试着将babel-loader的exclude注释掉,然后看能否打包成功.如果可以,那就是这个问题.你只需要在vue.config.js中配置transpileDependen ...
- android studio 使用 aidl(一)基础用法
最近公司需要开发一个项目用的到aidl,之前研究过eclipse版本的,但是好久了一直没用,现在需要捡起来,但是现在都用android studio了,所以查了下资料 都不是很全,我在这里总结一下,方 ...
- 常见排序——Java实现
1 package struct; 2 3 /** 4 * 5 * @作者:dyy 6 * @公司:陕西科技大学 7 * @修改日期: 8 * @邮箱:1101632375@qq.com 9 * @描 ...
- lambda表达式快速创建
Java 8十个lambda表达式案例 1. 实现Runnable线程案例 使用() -> {} 替代匿名类: //Before Java 8: new Thread(new Runnable( ...