算法学习:leetcode 1 two-sum 两数之和之go语言实现

0x00 题干

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

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

0x01 分析

**题目大意:**给出一个数组以及目标值,在这个数组中找相关的两个数,确保两个数的和与目标值相等,返回这两个数的下表

**思路:**很简单,两层遍历,找到对应的值即可。当然可以使用map进行优化。

0x02 题解

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

代码实现见:https://github.com/totalo/leetcode-go/blob/master/two-sum.go

你可能感兴趣的:(算法学习,go,leetcode)