jjzjj

go - twoSum 函数对不同的数组输入有不同的行为

当我运行以下代码时,我得到了预期的答案[3,4],这是加起来成为我的目标变量的2个数字的索引。但是,当我将myArray输入更改为[]int{1,2,3,4,6,11,4,12}(我删除了最后6个)时,我感到panic。请帮助我理解为什么会这样。functwoSum(nums[]int,targetint)[]int{length:=len(nums)-1fori:=rangenums[:length]{forj:=rangenums[i+1:]{ifnums[i]+nums[j]==target{return[]int{i,j}break}}}panic("shouldneverha

java - twoSum 算法 : How to improve this?

想做个算法,在leetcode上发现了这个问题Givenanarrayofintegers,findtwonumberssuchthattheyadduptoaspecifictargetnumber.ThefunctiontwoSumshouldreturnindicesofthetwonumberssuchthattheyadduptothetarget,whereindex1mustbelessthanindex2.Pleasenotethatyourreturnedanswers(bothindex1andindex2)arenotzero-based.Youmayassume