题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

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.

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解题思路:

  • 暴力穷举:外循环遍历每个元素 x,内循环查找是否存在一个值与 target - x 相等的目标元素,返回相等的目标元素和 x 的索引。时间复杂度 O (n^2),效率太低,pass。

  • 哈希表:哈希映射(map、dict),key 保存该元素,value 保存该元素索引。

    • 两次遍历法:第一次遍历把所有元素及其索引保存到哈希映射,第二次遍历查找 target - x 相等的目标元素

    • 一次遍历法:假如 y = target - x,则 x = target -y,所以一次遍历 在存入哈希映射的同时查找是否存在一个值与 target - x 相等的目标元素。

      例:nums = [2, 11, 7, 15], target = 9, hashmap = { }
      遍历:
      i = 0: target - x = 9 - 2 = 7, 7 不存在于 hashmap 中,则 x(2) 加入 hashmap, hashmap = {2 : 0}
      i = 1: target - x = 9 - 11 = -2, -2 不存在于 hashmap 中,则 x(-2) 加入 hashmap, hashmap = {2 : 0, 11 : 1}
      i = 2: target - x = 9 - 7 = 2, 2 存在于 hashmap 中,则返回列表 [2, 0]

代码:

两次遍历(Java):

class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {//一次遍历转换成键值对,key为元素值,value为索引值
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {//二次遍历查找符合条件的元素
int res = target - nums[i];
if (map.containsKey(res) && map.get(res) != i) {//查找到的目标元素不能为其本身
return new int[]{i, map.get(res)};
}
}
return null;
}
}

一次遍历 (Java):

class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int res = target - nums[i];
if (map.containsKey(res)) {//因为自身元素还未加入到 hashmap,无需 map.get(res) != i 条件判断
return new int[]{i, map.get(res)};
}
map.put(nums[i], i);//未找到目标元素则将其加入 hashmap
}
return null;
}
}

一次遍历 (Python):

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i, num in enumerate(nums): #枚举 nums 数组
if num in dic:
return [dic[num], i]
else:
dic[target-num] = i

利用 Python 数组自带 index 方法解题:

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i, num in enumerate(nums):
if target-num in nums and nums.index(target-num) != i:
return [i, nums.index(target-num)]

list.index():

描述:

index () 函数用于从列表中找出某个值第一个匹配项的索引位置。

语法:

index () 方法语法:

list.index(x, start, end)

参数:

  • x-- 查找的对象。
  • start-- 可选,查找的起始位置。
  • end-- 可选,查找的结束位置。

返回:

该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。

欢迎关注微.信.公.众号: 爱写Bug

LeetCode 1:两数之和 Two Sum的更多相关文章

  1. LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)

    653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...

  2. LeetCode:两数之和、三数之和、四数之和

    LeetCode:两数之和.三数之和.四数之和 多数之和问题,利用哈希集合减少时间复杂度以及多指针收缩窗口的巧妙解法 No.1 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在 ...

  3. 领扣-1/167 两数之和 Two Sum MD

    Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...

  4. 前端与算法 leetcode 1. 两数之和

    目录 # 前端与算法 leetcode 1. 两数之和 题目描述 概要 提示 解析 解法一:暴力法 解法二:HashMap法 算法 传入[1, 2], [11, 1, 2, 3, 2]的运行结果 执行 ...

  5. Leetcode 001. 两数之和(扩展)

    1.题目要求 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 2.解法一:暴力法(for*for,O(n*n)) ...

  6. leetCode:twoSum 两数之和 【JAVA实现】

    LeetCode 两数之和 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标. 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素. 更多文章查看个人博客 个人博客地址:t ...

  7. 【Leetcode】两数之和,三数之和,四数之和

    两数之和 题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这 ...

  8. Leetcode 1. 两数之和 (Python版)

    有粉丝说我一个学算法的不去做Leetcode是不是浪费,于是今天闲来没事想尝试一下Leetcode,结果果断翻车,第一题没看懂,一直当我看到所有答案的开头都一样的时候,我意识到了我是个铁憨憨,人家是让 ...

  9. 每天一道面试题LeetCode 01 -- 两数之和

    Two Sum 两数之和 Given an array of integers, find two numbers such that they add up to a specific target ...

  10. Leetcode 167. 两数之和 II - 输入有序数组 By Python

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2. 说明: 返回的下标值 ...

随机推荐

  1. PHP switch的写法

    switch switch (expression) { case label1: expression = label1 时执行的代码 ; break; case label2: expressio ...

  2. 表单生成器(Form Builder)之伪造表单数据mongodb篇

    这篇文章终于回到了正轨:为mongodb伪造数据.之前的随机数.随机车牌照.随机时间还有这篇笔记中的获取指定长度的中文字符串,都是为这篇笔记做准备.看一下我们的准备(基础代码) // 1.获取指定范围 ...

  3. [Go]TCP服务中读写进行协程分离

    读写两部分进行一下分离,中间通过chan进行传递数据 ,这样可以方便的在write中进行一些业务处理 single/snet/tcpconn.go package snet import ( &quo ...

  4. August 25th, 2019. Sunday, Week 35th.

    It's what you do next that counts, not what happens but what you decide to do about it. 重点不是发生了什么,而是 ...

  5. 08-Django 模板

    需要教程的请关注个人微信公众号 模板:产生html,用于控制页面的展示,模板不仅仅是一个html文件,它包含两部分内容: 静态内容:css,js,image 动态内容:用模板语言语言动态的产生一些网页 ...

  6. Mysql安装及常用命令

    部分内容转载于 https://www.linuxidc.com/Linux/2016-09/135288.htm https://www.cnblogs.com/rays-/p/8081798.ht ...

  7. IT兄弟连 HTML5教程 CSS3揭秘 CSS3概述

    对于Web开发者来说,CSS3不只是一门新奇的技术,更重要的是这些全新概念的Web应用给开发人员带来了无限的可能性,也极大地提高了开发效率.我们不必再依赖图片或者JavaScript去完成圆角.多背景 ...

  8. Elasticsearch 6.x版本全文检索学习之聚合分析入门

    1.什么是聚合分析? 答:聚合分析,英文为Aggregation,是es除搜索功能外提供的针对es数据做统计分析的功能.特点如下所示: a.功能丰富,提供Bucket.Metric.Pipeline等 ...

  9. Add a Simple Action添加简单按钮

    In this lesson, you will learn how to create a Simple Action. For this purpose, a new View Controlle ...

  10. JS基础语法---JSON格式的数据

         1. 对象: 有属性和方法,特指的某个事物     对象: 一组无序属性的集合的键值对,属性的值可以是任意的类型   2.JSON格式的数据:一般都是成对的,是键值对,     json也是 ...