4

LeetCode_Go

 1 year ago
source link: https://shaoyuanhangyes.github.io/2023/04/16/LeetCode-Go/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

LeetCode_Go

2023-04-16Go

从Github仓库搬运到Hexo 整合到此

1.两数之和 two sum

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

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

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

import "fmt"

func twoSum(nums []int, target int) []int {
m := map[int]int{}
for k, v := range nums {
if p, ok := m[target-v]; ok {
return []int{p, k}
}
m[v] = k
}
return []int{}
}

func main() {
nums := []int{2, 7, 11, 15}
target := 9
result := twoSum(nums, target)
fmt.Println(result)
}
End of reading! -- Thanks for your supporting

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK