GoLang, 原创, ,

【算法】两数之和(GoLang)

两数之和 题目和测试地址: https://leetcode-cn.com/problems/two-sum/

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

GoLang 实现如下

func twoSum(nums []int, target int) []int {
	count := len(nums)
	if count < 2 {
		return []int{}
	}
	hashMap := make(map[int]int)
	for index, num := range nums {
		another_num := target - num
		if _,ok := hashMap[another_num]; ok {
			return []int{hashMap[another_num], index}
		}
		hashMap[num] = index
	}
	return []int{}
}

执行用时 :4 ms, 在所有 golang 提交中击败了97.99%的用户
内存消耗 :3.7 MB, 在所有 golang 提交中击败了46.55%的用户

(178)

Related Post