【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,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
随机推荐
- 【3】蛋白鉴定软件之Mascot
目录 1.简介 2.配置 2.1在线版本 2.2 服务器版本 3.运行 3.1 在线版本 3.2 服务器版本 4.结果 1.简介 Mascot是非常经典的蛋白鉴定软件,被Frost & Sul ...
- Golang: map类型切片内存分配
切片ik通过索引访问,然后为每个map分配内存: 切片jk通过获得切片内每个元素的拷贝来分配内存,并未成功为切片内每个map分配内存,使用时赋值也就失败了 1 package main 2 3 imp ...
- STM32驱动直流电机的程序与电路设计(IR2110S自举电路+H桥+高级定时器和死区PWM)
https://blog.csdn.net/geek_monkey/article/details/82079435
- 56-Remove Linked List Elements
Remove Linked List Elements My Submissions QuestionEditorial Solution Total Accepted: 61924 Total Su ...
- Oracle完整的压测记录
问题描述:对oracle进行一次完整的数据压测,从制造数据到压测的过程,路上踩了一些坑,现在分享出来 1.下载swingbenh软件,一个比较好用的oracle压测软件 2.利用oewizard工具( ...
- linux下定位异常消耗的线程实战分析
前言: 之前分享过一篇Linux开发coredump文件分析实战分享 ,今天再来分享一篇实战文章. 在我们嵌入式linux开发过程中,开发过程中我们经常会使用多进程.多线程开发.那么多线程使用过程中, ...
- 商业爬虫学习笔记day4
一.获取登录后页面信息的两种方法 1.第一种方法: 人为把有效cookies加到请求头中,代码如下 import urllib.request # 确定url url = "https:// ...
- k8s-hpa自动横向扩容
目录 hpa自动扩容 官方文档 HPA是什么 Horizontal Pod Autoscaler 演练 参数 案例:监控cpu,内存,每秒数据包自动扩容 度量指标 pod清单案例-pod定义cup内存 ...
- Oracle LOB类型
一.Oracle中的varchar2类型1.我们在Oracle数据库存储的字符数据一般是用VARCHAR2.VARCHAR2既分PL/SQL Data Types中的变量类型,也分Oracle Dat ...
- linux修改文件权限命令
先看个实例: [root@local opt]#ls -al ls -al 命令是列出目录的所有文件,包括隐藏文件.隐藏文件的文件名第一个字符为'.' -rw-r--r-- 1 root root ...