首页 > 其他分享 >1. Two Sum #

1. Two Sum #

时间:2022-08-24 16:03:44浏览次数:67  
标签:return target nums int Sum Two another 数字

1. Two Sum #

题目 #

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]

题目大意 #

在数组中找到 2 个数之和等于给定值的数字,结果返回 2 个数字在数组中的下标。

解题思路 #

这道题最优的做法时间复杂度是 O(n)。

顺序扫描数组,对每一个元素,在 map 中找能组合给定值的另一半数字,如果找到了,直接返回 2 个数字的下标即可。如果找不到,就把这个数字存入 map 中,等待扫到“另一半”数字的时候,再取出来返回结果。

代码 #

Go

package leetcode

func twoSum(nums []int, target int) []int {
	m := make(map[int]int)
	for i := 0; i < len(nums); i++ {
		another := target - nums[i]
		if _, ok := m[another]; ok {
			return []int{m[another], i}
		}
		m[nums[i]] = i
	}
	return nil
}

标签:return,target,nums,int,Sum,Two,another,数字
From: https://www.cnblogs.com/suehoo/p/16620304.html

相关文章

  • np.sum()
    np.sum(a,axis=None,dtype=None,out=None,keepdims=np._NoValue)参数:a:用于进行加法运算的数组形式的元素。axis:\(axis\)的取值有三种情况:1.\(None\),2.整数,3.......
  • js 实现 sum 函数无限累加
    //无限累加sum//一共做两件事://1.调用一次返回当前计算函数本身,该函数主要作用之一为合并多次调用传的不同数量的参数//2.给返回的函数增加valueOf最终计算结......
  • NC24953 [USACO 2008 Jan G]Cell Phone Network
    题目链接题目题目描述FarmerJohnhasdecidedtogiveeachofhiscowsacellphoneinhopestoencouragetheirsocialinteraction.This,however,requireshi......
  • 【笔记】EG3D: Efficient Geometry-aware 3D Generative Adversarial Networks
    EG3D:EfficientGeometry-aware3DGenerativeAdversarialNetworksIntroduction使用单视角2D图片集,无监督地生成高质量且视角一致性强的3D模型,一直以来都是一个挑战。......
  • PowerShell教程 - 网络管理(Network Management)
    更新记录转载请注明出处。2022年8月23日发布。2022年8月18日从笔记迁移到博客。网络管理(NetworkManagement)获得网卡信息Get-NetAdapter测试网络连通性实例:......
  • Attentional Factorization Machines: Learning the Weight of Feature Interactions
    动机本文是2017年IJCAI上的一篇论文。FM方法通过结合二阶特征交互来增强线性回归模型,它将这些特征交互一视同仁,给予它们一个相同的权重,但是并不是所有特征的交互都是有意......
  • 「PKUSC2021」Sum Transformation 解题报告
    题目描述定义矩阵变换 \(F(P)=Q\),其中 \(P\) 和 \(Q\) 是\(n×n\) 的矩阵且满足 \(Q_{i,j}=(\sum^{n}_{k=1}P_{k,j}+\sum_{k=1}^nP_{i,k})mod\spacep\)。给定 \(......
  • Maximum Segment Sum After Removals
    MaximumSegmentSumAfterRemovalsYouaregiventwo0-indexedintegerarrays$nums$and$removeQueries$,bothoflength$n$.Forthe$i^{th}$query,theeleme......
  • 函数式接口-常见函数式接口-Consumer接口
    常见函数式接口JDK提供了大量常用的函数式接口以丰富Lambda的经典使用常见它们注意在java.util.function包中被提供Consumer接口Consumer<T>接口则正好与Supplier接口......
  • summary
     代码示例:  ......