安康网站建设制作,人防门电气图纸符号大全久久建筑网,无人在线完整免费高清观看,淘宝客建设网站文章目录 题目代码解法2 代码仓库 题目
给定一个整数数组 nums 和一个整数目标值 target#xff0c;请你在该数组中找出 和为目标值 target 的那 两个 整数#xff0c;并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是#xff0c;数组中同一个元素在答案… 文章目录 题目代码解法2 代码仓库 题目
给定一个整数数组 nums 和一个整数目标值 target请你在该数组中找出 和为目标值 target 的那 两个 整数并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
代码
/** Author: JavaPub* Date: 2023-10-28 11:36:49* LastEditors: your name* LastEditTime: 2023-10-28 11:44:59* Description: Here is the JavaPub code base. Search JavaPub on the whole web.* FilePath: \Go-Learn-Algorithms\examples\simple\1\1.go*/// 第一道题就用两数求和来开始两数之和package mainimport fmtfunc main() {fmt.Println(twoSum([]int{3, 2, 4}, 6))
}func twoSum(nums []int, target int) []int {for i, v : range nums {for j, b : range nums {if vb target i ! j {return []int{i, j}}}}return []int{9, 9}
}
解法2
package mainimport fmtfunc main() {fmt.Println(twoSumV2([]int{2, 7, 11, 15}, 9))
}func twoSumV2(nums []int, target int) []int {for i, x : range nums {for j : i 1; j len(nums); j {if xnums[j] target {return []int{i, j}}}}return nil
}
代码仓库
https://github.com/Rodert/Go-Learn-Algorithms/tree/main/examples/simple/two-sum