烟台网站建设哪家服务好,怎么更换网站图片,如何提高网站排名seo,网页打不开怎么回事两数之和
题目#xff1a;1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target#xff0c;请你在该数组中找出 和为目标值 target 的那 两个 整数#xff0c;并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是#xff0c;数组中同一个元素在答案…两数之和
题目1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target请你在该数组中找出 和为目标值 target 的那 两个 整数并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1
输入nums [2,7,11,15], target 9
输出[0,1]
解释因为 nums[0] nums[1] 9 返回 [0, 1] 。示例 2
输入nums [3,2,4], target 6
输出[1,2]示例 3
输入nums [3,3], target 6
输出[0,1]提示
2 nums.length 104-109 nums[i] 109-109 target 109只会存在一个有效答案
**进阶**你可以想出一个时间复杂度小于 O(n2) 的算法吗
方法一
使用二元组解决问题。
type eryuanzu struct {Index intValue int
}func twoSum(nums []int, target int) []int {Len : len(nums)res : make([]int, 2)eryuanzus : make([]*eryuanzu, Len)// m 排序for i : 0; i Len; i {eryuanzus[i] eryuanzu{Index: i, Value: nums[i]}}for _, e : range eryuanzus {fmt.Println(e.Index, e.Value)}// 给二元组排序qSortForEryuanzu(eryuanzus, 0, Len-1)for _, e : range eryuanzus {fmt.Println(e.Index, e.Value)}l, r : 0, Len-1for l r {if eryuanzus[l].Valueeryuanzus[r].Value target {l} else if eryuanzus[l].Valueeryuanzus[r].Value target {r--} else {res[0] eryuanzus[l].Indexres[1] eryuanzus[r].Indexreturn res}}return res
}func qSortForEryuanzu(es []*eryuanzu, s, h int) {if s h {return}pos : positionForEryuanzu(es, s, h)qSortForEryuanzu(es, s, pos-1)qSortForEryuanzu(es, pos1, h)
}func positionForEryuanzu(es []*eryuanzu, s, h int) int {base : es[s]l, r : s, hfor l r {for l r es[r].Value base.Value {r--}es[l] es[r]for l r es[l].Value base.Value {l}es[r] es[l]}es[l] basereturn l
}使用快排时间复杂度O(nlogn)。空间复杂度消耗较大O(n)。
时间复杂度是符合进阶要求了是否还有更快的方法呢
我们如果遍历数组只需要知道当前遍历的元素有没有与之相加为target的数。那么我们就可以用哈希表来完成。
方法二
使用哈希表。
func twoSum(nums []int, target int) []int {m : make(map[int]int)for i, num : range nums {m[num] i}for i, num : range nums {if j, ok : m[target-num]; ok {if i ! j {return []int{i, j}}}}return nil
}