首页 > 其他分享 >1. Two Sum Go实现

1. Two Sum Go实现

时间:2024-06-12 20:43:40浏览次数:11  
标签:哈希 nums int Sum Two another 表中 Go data

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

1. 解法1 时间复杂度 O(n^2)

直接两次遍历所有节点,进行求和比较
代码如下:

func twoSum(nums []int, target int) []int {
	res := make([]int, 2, 2)
	for i:= 0;i<len(nums);i++{
		for j:=i+1;j<len(nums);j++{
			if nums[i]+nums[j]==target{
				res[0] =i
				res[1]=j
			}
		}
	}
	return res
}

2.解法2: 时间复杂度O(n)

只需要遍历一次所有元素,用 哈希表进行存储即可: 只要数字总和,那么每遍历一次数组,就可以算出他的求和的另一个数字的值,在接下来的遍历中如果找到了就成功得到答案,否则返回Nil

代码如下:

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

语法熟悉

Go多重赋值

if _, ok := m[another]; ok {

首先执行;前的内容,在Go中,根据键访问map会返回两个值,第一个值是这个键对应的值,第二个值是该键是否存在,如果存在返回True,否则False。接下根据OK是否为真判断是否进入后续语句。

return []int{data[another], i }

如果存在,就说明当前位置的元素的另一半存在于这个哈希表中,就访问成功了,那么找到满足要求的两个数,需要返回他俩的下标,这个哈希表中键是元素,值是下标,就返回即可。

如果没有找到另一半,就将这个元素加入到哈希表中,由于是在哈希表中查找,那么哈希表中的元素必然在原Array中位置靠前,所以应先返回哈希表中的元素。

标签:哈希,nums,int,Sum,Two,another,表中,Go,data
From: https://www.cnblogs.com/CharlseGo/p/18244678

相关文章

  • 基于GO语言,K8s+gRPC实战云原生微服务
    介绍K8s在云原生微服务开发中,作为微服务治理框架越来越受企业的青睐,掌握该技术解决方案更有竞争力,课程从企业实际开发中提取精髓,从K8s、gRPC底层原理剖析到服务治理解决方案设计落地,到云上部署,更平滑的学习曲线,助力你成为云原生开发领域的牛人。你将学到掌握整套K8s微服务......
  • C. Minimizing the Sum
    原题链接题解1.任何一个数,只能覆盖一次2.把被覆盖的数字具象化,那么最终数组一定是由若干个有颜色的区间(被覆盖)和无颜色区间(没有被覆盖)组成3.这里就是状态的巧妙之处了,已知我们要求\(n\)个数里最多\(k\)个数被覆盖的最小和,那么这\(k\)个数里,一定存在末尾连续\(j\)个数......
  • Go - pflag and viper
    pflagisadrop-inreplacementofGo'snativeflagpackage.Ifyouimportpflagunderthename"flag"thenallcodeshouldcontinuetofunctionwithnochanges.importflag"github.com/spf13/pflag"Thereisoneexceptiontothis:......
  • Dragon Boat Festival
    BeforetheDragonBoatFestival,mygrandmamadedozensofzongzimadeupofreedleaves,polishedglutinousriceandmeat.Mygrandmamakesdeliciouszongzieveryyear.Idon’tknowhowtomakeit.TheDragonBoatFestivalcamesilently.Onthemorning,......
  • go http请求
    funcSend(notificationmodel.Notification,defaultRobotstring)(errerror){markdown,robotURL,err:=transformer.TransformToMarkdown(notification)iferr!=nil{return}data,err:=json.Marshal(markdown)iferr!=nil{......
  • Anomaly Detection on Attributed Networks via Contrastive Self-Supervised Learnin
    PaperAnomalyDetectiononAttributedNetworksviaContrastiveSelf-SupervisedLearnin代码实现异常注入inject_anomaly.pyinject_anomaly.py注入异常过程,处理原始数据集,并添加结构和属性扰动,注入结构属性异常。importnumpyasnpimportscipy.sparseasspim......
  • Go版RuoYi
     RuoYi-Go  https://github.com/Kun-GitHub/RuoYi-Go1.关于我个人介绍2.介绍后端用Go写的RuoYi权限管理系统(功能正在持续实现)后端 Gitee地址3.前端RuoYi-Vue3官方前端Vue3版4.Go后端技术栈(持续在对齐项目,在补充)功能框架是否采用备注配置......
  • The dragon Boat Festival
    TheDragonBoatFestival,alsoknownastheDuanwuFestival,isatraditionalChineseholidaycelebratedonthefifthdayofthefifthmonthofthelunarcalendar.ItfallsonJune3rdthisyear.Thisfestivalhasahistoryspanningover2000yearsandis......
  • Dragon Boat Festival
    essenceofthisfestivalAsweallknow,DragonBoatFestivalisatraditionalchinesefestivaltoshowourrespecttoQuYuan.Dragonboatracing,eatingzongzi,prayingforblessings,andwardingoffevilthingsarethecustomthemesoftheDragonBoat......
  • Dragon Boat Festival
    AstheDragonBoatFestivalapproaches,ourcommunityburstswithexcitementandanticipationforthisholiday.Inmyeyes,thisfestivalisrootedinourChinesehistoryandcultureandisfamouswithawell-knownpeoplecalledQuyuan.Inourcommunity,......