目标 工作后时间比较少了,也不知道能不能坚持下来,给自己定个小目标吧。每天至少一道题。
01 twoSum
思路:暴力法 时间复杂度O(n^2) 直接遍历两遍数组(nums),选择满足条件的值,加入结果数组(res)。 Go语言关键字range支持索引与结果同时输出,感觉还是比较方便的。
遍历数组:
for i ,j:= range nums{
//do something
}
package main
//Given an array of integers, return indices of the two numbers such that they a
//dd up to a specific target.
//
// You may assume that each input would have exactly one solution, and you may n
//ot 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].
//
// Related Topics 数组 哈希表
// 👍 8695 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
func twoSum(nums []int, target int) []int {
res := []int{}
for i ,value1:= range nums {
for j ,value2:= range nums[i+1:]{
if value1+value2 == target{
res = append(res, i,j+i+1)
}
}
}
return res
}
//leetcode submit region end(Prohibit modification and deletion)