首页 > 试题广场 >

两数之和

[编程题]两数之和
  • 热度指数:401430 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给出一个整型数组 numbers 和一个目标值 target,请在数组中找出两个加起来等于目标值的数的下标,返回的下标按升序排列。
(注:返回的数组下标从1开始算起,保证target一定可以由数组里面2个数字相加得到)

数据范围:
要求:空间复杂度 ,时间复杂度
示例1

输入

[3,2,4],6

输出

[2,3]

说明

因为 2+4=6 ,而 2的下标为2 , 4的下标为3 ,又因为 下标2 < 下标3 ,所以返回[2,3]            
示例2

输入

[20,70,110,150],90

输出

[1,2]

说明

20+70=90     
头像 ajaj
发表于 2021-07-18 17:05:51
精华题解 思路: 从题中给出的有效信息: 找出下标对应的值相加为target 数组中存在唯一解 故此 可以使用 直接遍历 或者 hash表 来解答 方法一:直接遍历 具体做法:循环遍历数组的每一个数,如果遍历的两数之和等于target,则返回两个数的下标; import java.util.*; publ 展开全文
头像 牛客786963925号
发表于 2021-07-07 18:19:31
精华题解 解法一:暴力解法 暴力解法的思路较为直接,在输入数组中分别对两个下标进行遍历,若满足题目要求,直接返回结果(题目中明确说明假设答案唯一)。 注意: 第一层循环应从0到n-2位置(n为数组长度),即不需要遍历到数组最后一个元素; 第二层循环应将第一层循环变量作为起点,遍历至数组最后一个元素。 下标从 展开全文
头像 牛客题解官
发表于 2022-04-22 12:22:00
精华题解 题目主要信息: 题目给出的是一个数组和一个目标值,需要我们在数组中找到两个加起来等于目标值的数组元素的下标 下标按升序排列,从1开始 举一反三: 学习完本题的思路你可以解决如下题目: BM54. 三数之和 方法:哈希表(推荐使用) 知识点:哈希表 哈希表是一种根据关键码(key)直接访问值(va 展开全文
头像 文卿周槐芳
发表于 2020-11-03 10:24:06
写个题解。原思路: 首先想到能不能排序。若是有序数组,将会节省不小的时间开销(target/2往后的不用看;每轮一旦两数和大于 target 即可 break)。 再看题目要求输出 index,若先排序 index 就乱了,貌似没戏。 还不死心,想能不能通过 Map 来存取改动前的 index。 展开全文
头像 失败的cc
发表于 2020-12-22 11:03:05
import java.util.*; public class Solution { public int[] twoSum (int[] numbers, int target) { int[] result = new int[2]; Map<I 展开全文
头像 数据结构和算法
发表于 2021-03-21 12:59:43
1,暴力破解法 就是使用两个for循环,这种效率很差 public int[] twoSum(int[] nums, int target) { int length = nums.length; for (int i = 0; i < length - 展开全文
头像 进一步有进一步的欢喜
发表于 2021-12-08 00:49:21
梦开始的地方 class Solution: def twoSum(self , numbers: List[int], target: int) -> List[int]: # write code here value2index = {} # 展开全文
头像 喝牛奶的牛
发表于 2020-03-10 19:39:14
题目描述: 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 h 展开全文
头像 小洋芋热爱NLP
发表于 2021-01-09 21:35:14
- 1、题目描述: - 2、题目链接: https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f?tpId=117&&tqId=34983&rp=1&ru=/ta/job-code-high 展开全文
头像 startsfdsfsfs
发表于 2021-01-27 16:21:21
谁说一定要全部建立好hashMap以后才能开始查找呢?大家可以观察一下,以下的代码~ 上代码 (python3) class Solution: def twoSum(self, numbers, target): # write code here if l 展开全文
头像 Yang760724227
发表于 2021-12-27 17:15:50
思路: 使用map这个数据结构,map用法: let map = new Map() map.set(1,2) // 1 => 2 map.get(1) // 2 map.has(1) // true 循环numbers数组,将numbers[i]加入map,它的值为i+1(因为索引要 展开全文
头像 牛客927056750号
发表于 2021-09-26 15:58:17
# # # @param numbers int整型一维数组 # @param target int整型 # @return int整型一维数组 # class Solution: def twoSum(self , numbers , target ): # writ 展开全文
头像 摸鱼学大师
发表于 2021-07-14 21:23:07
思路: 题中可以看出: 必定存在唯一解,不用考虑特殊情况 返回的下标是数组下标加1 最能想到的办法莫过于暴力解决,直接遍历两层循环,相加与target比较,若相同则跳出循环。 方法一:暴力比较法 class Solution { public: vector<int> two 展开全文