两数之和
func twoSum(nums []int,target int)[]int{
maps := make(map[int]int)
for index,value := range nums {
member := target - value
if _,err := maps[member] ; err {
return []int{index,maps[member]}
}else {
maps[value] = index
}
}
return []int{}
}
三数之和
func threeNum(nums []int,target int)[][]int {
if len(nums) < 3 {
return [][]int{}
}
sort.Ints(nums)
result := [][]int{}
for i := 0 ;i < len(nums) ;i++ {
if i < len(nums) -2 && nums[i] - nums[i+1] == 0{
continue
}
j := i+1
k := len(nums)-1
for j<k {
tempNum := nums[i] + nums[j] + nums[k]
if tempNum < target {
j++
}
if tempNum> target {
k--
}
if tempNum == target {
fmt.Println(nums[i] , nums[j] , nums[k])
result = append(result,[]int{nums[i] , nums[j] , nums[k]})
for j<k && nums[j] == nums[j+1] {
j++
}
for j<k && nums[k] == nums[k-1] {
k--
}
j++
k--
}
}
}
return result
}