• 作者: 负雪明烛
  • 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 两数之和的更多相关文章

  1. [LeetCode] 1. Two Sum 两数之和

    Part 1. 题目描述 (easy) Given an array of integers, return indices of the two numbers such that they add ...

  2. [LeetCode]1.Two Sum 两数之和&&第一次刷题感想

    ---恢复内容开始--- 参考博客: https://www.cnblogs.com/grandyang/p/4130379.html https://blog.csdn.net/weixin_387 ...

  3. [LeetCode] 1.Two Sum 两数之和分析以及实现 (golang)

    题目描述: /* Given an array of integers, return indices of the two numbers such that they add up to a sp ...

  4. 【LeetCode】Two Sum(两数之和)

    这道题是LeetCode里的第1道题. 题目描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会 ...

  5. [leetcode]1. Two Sum两数之和

    Given an array of integers, return indices  of the two numbers such that they add up to a specific t ...

  6. [LeetCode]1.Two Sum 两数之和(Java)

    原题地址:two-sum 题目描述: 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标. 你可以假设每 ...

  7. 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 ...

  8. Leetcode:0002(两数之和)

    LeetCode:0002(两数之和) 题目描述:给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表.你可以假设除了数字 0 之外,这两 ...

  9. Leetcode(1)两数之和

    Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...

随机推荐

  1. EXCEL-时间

    1.时间的3中输入方法: (1)手打输入: (2)快捷键:[快,方便,且结果跟手打一样,不会改变][Ctrl+;]->年月日    [Ctrl+:]->时分秒(我这里是这样的效果) (3) ...

  2. adblock plus-看下图你就懂

  3. 浅讲.Net 6 之 WebApplicationBuilder

    介绍 .Net 6为我们带来的一种全新的引导程序启动的方式.与之前的拆分成Program.cs和Startup不同,整个引导启动代码都在Program.cs中. WebApplicationBuild ...

  4. JDBC(1):JDBC介绍

    一,JDBC介绍 SUN公司为了简化.统一对数据库的操作,定义了一套Java操作数据库的规范(接口),称之为JDBC.这套接口由数据库厂商去实现,这样,开发人员只需要学习jdbc接口,并通过jdbc加 ...

  5. entfrm-app赋能entfrm零代码开发平台 开启多平台分发

    entfrm-app是基于uni-app 框架.使用 Vue.js 语法开发的移动端 App开源产品.它可以编译为 H5.IOS App.Android App.微信小程序.QQ小程序.钉钉小程序.支 ...

  6. Hadoop生态圈学习-1(理论基础)

    一.大数据技术产生的背景 1. 计算机和信息技术(尤其是移动互联网)的迅猛发展和普及,行业应用系统的规模迅速扩大(用户数量和应用场景,比如facebook.淘宝.微信.银联.12306等),行业应用所 ...

  7. 【Linux】【Shell】【Basic】条件测试和变量

    bash脚本编程       脚本文件格式:         第一行,顶格:#!/bin/bash         注释信息:#         代码注释:         缩进,适度添加空白行:   ...

  8. Cnblog博客美化

    具体的使用教程文档在这里 BNDong/Cnblogs-Theme-SimpleMemory 简要的操作如下: 博客园 - 管理 - 设置 值得注意得是: 要想JS代码要申请才可以使用 博客侧边栏 可 ...

  9. 多媒体音视频处理及FFmpeg使用技巧总结

    截图 ffmpeg -ss 00:02:06 -i input.mp4 -f image2 -y poster.jpg 连续截图 ffmpeg -y -i input.mp4 -vf "fp ...

  10. 在html页面通过绝对地址显示图片

    1.编辑tomcat中conf目录下的server.xml文件,在<Host></Host>中添加如下代码段 <Context path="/D" d ...