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.
Example & Constraints:
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
// 这个范例应该是错误的,出现了相同的元素
Input: nums = [3,3], target = 6
Output: [0,1]
Constraints:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
packageleetcodeimport("math/rand""testing""time")const(maxVal=109maxTargetVal=109minArrLen=2maxArrLen=104)functwoSum(nums[]int,targetint)[]int{m:=make(map[int]int)forindex,num:=rangenums{ifi,ok:=m[target-num];ok{return[]int{i,index}}m[num]=index}returnnil}functwoSumBruce(nums[]int,targetint)[]int{fori:=0;i<len(nums)-1;i++{forj:=i+1;j<len(nums);j++{ifnums[i]+nums[j]==target{return[]int{i,j}}}}returnnil}funcgenerateNum(maxint)int{r:=rand.New(rand.NewSource(time.Now().UnixNano()))returnr.Intn(max<<1+1)-max}funcgenerateArray(targetint,maxint)[]int{arrLen:=rand.Intn(maxArrLen-minArrLen+1)+minArrLenarr:=make([]int,arrLen)varnum1,num2intset:=make(map[int]struct{})num1=generateNum(max)num2=generateNum(max)set[num1]=struct{}{}fornum2==num1{num2=generateNum(max)}set[num2]=struct{}{}arr[0]=num1arr[1]=num2fori:=2;i<arrLen;i++{randNum:=generateNum(max)for{// 元素没有重复且和已有的元素相加不能为target值
if_,ok:=set[randNum];!ok{if_,ok:=set[target-randNum];!ok{break}}randNum=generateNum(max)}set[randNum]=struct{}{}arr[i]=randNum}r:=rand.New(rand.NewSource(time.Now().UnixNano()))r.Shuffle(len(arr),func(i,jint){arr[i],arr[j]=arr[j],arr[i]})returnarr}funcisEqual(arr1[]int,arr2[]int)bool{iflen(arr1)!=len(arr2){returnfalse}fori,v:=rangearr1{ifarr2[i]!=v{returnfalse}}returntrue}funcTestTwoSum(t*testing.T){arr:=generateArray(maxTargetVal,maxVal)fori:=0;i<100000;i++{expectedRes:=twoSumBruce(arr,maxTargetVal)res:=twoSum(arr,maxTargetVal)if!isEqual(expectedRes,res){t.Fatalf("input arr is :%v\n expect result is :%v but got %v\n",arr,expectedRes,res)}}t.Log("Test TwoSum Success!\n")}