题目

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

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

你可以假设每种输入只会对应一个答案,且数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

Constraints:

  • 2 <= nums.length <= 1 0 4 10^4 104
  • - 1 0 9 10^9 109 <= nums[i] <= 1 0 9 10^9 109
  • - 1 0 9 10^9 109 <= target <= 1 0 9 10^9 109
  • Only one valid answer exists.

提示:

  • 2 <= nums.length <= 1 0 4 10^4 104
  • - 1 0 9 10^9 109 <= nums[i] <= 1 0 9 10^9 109
  • - 1 0 9 10^9 109 <= target <= 1 0 9 10^9 109
  • 只会存在一个有效答案

Follow-up:

Can you come up with an algorithm that is less than O( n 2 n^2 n2) time complexity?

进阶:

你可以想出一个时间复杂度小于 O( n 2 n^2 n2) 的算法吗?

解题思路

方法一:暴力

我们通过遍历数组每个元素x,寻找tatget-x,且数组每个元素只能出现一次所以只要寻找x后面的元素。

Python代码

class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:n = len(nums)for i in range(n):for j in range(i + 1, n):if nums[i] + nums[j] == target:return [i, j]return []

Java代码

class Solution {public int[] twoSum(int[] nums, int target) {int n = nums.length;for (int i = 0; i < n; i++) {for (int j = i + 1; j < n; j++) {if (nums[i] + nums[j] == target) {return new int[]{i, j};}}}return new int[0];}
}

C++代码

class Solution {public:vector<int> twoSum(vector<int>& nums, int target) {int n = nums.size();for (int i = 0; i < n; i++) {for (int j = i + 1; j < n; j++) {if (nums[i] + nums[j] == target) {return {i, j};}}}return {};}
};

复杂度分析

  • 时间复杂度:O( n 2 n^2 n2),其中 n 是数组中的元素数量。
  • 空间复杂度:O(1)。

方法二:哈希表

我们使用哈希表 key存储数组的值,value存储数组值的下标从而遍历判断target-x是否存在哈希表中

  • 若不存在哈希表中,则将数组的值和下标加入哈希表
  • 若存在哈希表中,则返回下标

Python代码

class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:hashtable = dict()for i, num in enumerate(nums):if target - num in hashtable:return [hashtable[target - num], i]hashtable[nums[i]] = ireturn []

Java代码

class Solution {public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();for (int i = 0; i < nums.length; ++i) {if (hashtable.containsKey(target - nums[i])) {return new int[]{hashtable.get(target - nums[i]), i};}hashtable.put(nums[i], i);}return new int[0];}
}

C++代码

class Solution {public:vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int, int> hashtable;for (int i = 0; i < nums.size(); ++i) {auto it = hashtable.find(target - nums[i]);if (it != hashtable.end()) {return {it->second, i};}hashtable[nums[i]] = i;}return {};}
};

复杂度分析

时间复杂度:O( n n n),其中 n 是数组中的元素数量。

空间复杂度:O( n n n),其中 n 是数组中的元素数量。

1. (Two Sum)两数之和相关推荐

  1. Two Sum (两数之和) - Hash Table (哈希表)

    Two Sum (两数之和) - Hash Table (哈希表) https://leetcode-cn.com/problems/two-sum/ Given an array of intege ...

  2. LeetCode in Python-1. Two Sum 两数之和

    Two Sum 两数之和 题目描述 解法1.切片后查找 解法2.hash字典 解法3.同2 出处 题目描述 解法1.切片后查找 class Solution:def twoSum(self, nums ...

  3. [Leetcode]Two sum(两数之和)系列总结

    Two sum 题目 Given an array of integers, return indices of the two numbers such that they add up to a ...

  4. leetcode之Tow Sum两数之和的三种思路

    双重循环.桶排序.HashMap 题目链接:两数之和 1.双重循环,最基本的方法,速度慢O(n^2),但无需新空间. public int[] twoSum(int[] nums, int targe ...

  5. 0001-Two Sum(两数之和)

    这个系列算是出于个人兴趣开的一个新坑吧,最近看到同学刷LeetCode算法题,就想写写那些可以一行Python代码写出来的题目,因此本专栏的文章的解题方式效率不做保证,只为追求"一行的浪漫& ...

  6. LeetCode刷题-两数之和(持续更新)

    文章目录 LeetCode 1. Two Sum (两数之和) 题目描述 样例 解题思路一(暴力法) 解题思路二(使用map) 前言:最近业余时间,一直在看LeetCode上面的题,上面有许多好的解题 ...

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

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

  8. leetcode算法—两数之和 Two Sum

    关注微信公众号:CodingTechWork,一起学习进步. 题目 Two Sum: Given an array of integers, return indices of the two num ...

  9. 167. Two Sum II - Input array is sorted两数之和

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

  10. 两数之和(Two Sum)

    文章目录 题目 一.暴力算法 二.利用hashMap键的唯一性 题目 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回 ...

最新文章

  1. mysql不等于判断时,空值过滤问题
  2. Flow - JS静态类型检查工具
  3. mysql中OPTIMIZE TABLE的作用
  4. 长江存储年底提供自研32层堆叠3D NAND闪存样品
  5. 使用百度webuploader插件进行多文件类型分片上传实例
  6. 谁将掌控中国的金融?(上)
  7. SpringBoot文件上传异常之提示The temporary upload location xxx is not valid
  8. LuaForUnity9:uLua的一个简单实例
  9. CFA难度:特许金融分析师CFA难考吗?
  10. java中j是什么意思_i 1 j 是什么意思 i.j.k是什么意思
  11. 【目标跟踪】|STARK
  12. 《图像超分辨率研究综述》笔记
  13. JAVA学习资源种子
  14. Unity3D使用鼠标旋转缩放平移视角
  15. Springboot快递管理系统1k61h计算机毕业设计-课程设计-期末作业-毕设程序代做
  16. html中让两段文字并列排放,言语理解:探究阅读之并列文段
  17. [Python]安装/升级pip/pip3
  18. git 提交修改备注
  19. [渝粤教育] 西南交通大学 体育健康课程Ⅰ—奥运裁判带你学规则 参考 资料
  20. 大衍筮法-python实现

热门文章

  1. AUTOSAR基础篇之Event(上)
  2. java.lang.IllegalStateException:Failed to build unique file: /storage/emulated/0/...
  3. Android 展示一个图片,可以双击放大/缩小(放大后可以移动)
  4. 21计算机考研时间,湖北2020计算机考研初试成绩公布时间2月21日起
  5. SAP HR 年休假调整:从统休制到实休制,在一个自然年度内分段式生成年休假
  6. 外汇投资新手必看!这些交易技巧帮你轻松入门
  7. UOJ Test Round 1
  8. 直接体绘制(Direct Volume Rendering)原理
  9. (附源码)spring boot网上投票系统 毕业设计 282018
  10. 电脑时间不同步解决方法