leetcode two numbers and go language

Two numbers (Go Language)

Given an integer array nums and a target value target, and ask you to identify the target value of the two integers in the array, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

The first solution (on2)

func twoSum(nums []int, target int) []int {
count:=len(nums)
var arr []int
for i:=0;i<count;i++{
for j:=i+1;j<count;j++{
if (nums[i]+nums[j]==target) {
arr=[]int{i,j}
break
}
}
}

return arr

}

The second solution

Space for time

func twoSum(nums []int,target int) []int {
//定一个map集合,然后将值为索引,健为值
var maps=make(map[int]int)
var arr []int
//将值赋给map集合
for k,i:=range nums{
maps[i]=k
}

//判断是否存在
for k,i:=range nums{
curnt:=target-i;
x1,x2:=maps[curnt]
if(x2 && x1!=k) {
arr=[]int{x1,k}
}
}

return arr

}

Guess you like

Origin www.cnblogs.com/mengluo/p/11273030.html