题目

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. python等号语法错误_Python干货:代码编写规范
  2. Linux整合Apache和SVN
  3. MySQL基本操作及乱码问题的解决方法
  4. linux route命令的使用详解(转)
  5. 安川机器人焊枪切换设定方法_安川机器人参数更改方法
  6. 看完此文章若你还不能完美的入门Python,我将永远退出IT界
  7. 将SSM架构中原来关于springSecurity3.x版本的写法配迁移到SpringBoot2.0框架中出现的问题解决记...
  8. Unity 叉乘 vector3 四元数 和声音组件
  9. 罗永浩关联直播交易案遭“问停”;中国量子计算原型机“九章”问世;pip 20.3 发布 | 极客头条...
  10. 英特尔处理器曝出重大安全漏洞,迫使 Linux 和 Windows 更新设计
  11. (转载)Mac系统下利用ADB命令连接android手机并进行文件操作
  12. 如何测试判断云服务器的稳定性?
  13. Atitit 减少财政支出之减少通讯支出 解决方案attilax总结
  14. 23 Pictures That Prove Society Is Doomed
  15. ipsec ikev2 中转
  16. 人工智能ai的有关专业术语_您需要知道的11个人工智能术语
  17. wishbone协议(B.3)下载地址
  18. 设置导航栏字体大小,颜色和加粗字体的方法
  19. [SCI][计算机视觉][图像处理]一二三四区期刊(自用)
  20. 【Python】turtle海龟画图练习

热门文章

  1. php reflectionclass 得到参数,PHP 返回 ReflectionClass 对象字符串的表示形式。
  2. mybatis查询子表
  3. 【Python】72行实现代码行数统计,简单实用~
  4. SEAM学习(八)---Seam应用程序框架
  5. 几个比较稳定可靠的网络硬盘(免费)
  6. GO入门指南:4.4章节练习题4.1、4.2、4.3习题分析
  7. 利用递归求两个数字的最大公约数
  8. 难道是360安全卫士惹的祸?
  9. 超炫15分钟超现实主义短片《Sundays》
  10. 小智报告 | 2020反洗钱处罚1季度报告