Abstract: Recently, I started to use the Go language to brush the leetcode topic, and interested friends can team up to brush it together. This article was first published on the public account: GoGuider
Title description-the sum of two numbers
Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts.
You can assume that each input will only correspond to one answer. However, the same element in the array cannot be repeated in the answer.
You can return the answers in any order.
Example 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
Example 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
Example 3:
输入:nums = [3,3], target = 6
输出:[0,1]
hint:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
Answer analysis
1. Violent solution
func twoSum(nums []int, target int) []int {
numsLen := len(nums)
for i, num := range nums {
for j := i + 1; j < numsLen; j++ {
if target == num + nums[j] {
return []int{i, j}
}
}
}
return []int{}
}
Time complexity: O(nlogn)
Space complexity: O(1)
2. Using the map method, the value of nums is inverted index, and the space is exchanged for time. The time complexity is O(n)
func twoSum(nums []int, target int) []int {
numsMap := make(map[int]int)
for index, num := range nums{
numsMap[num] = index
}
for index, num := range nums {
if preIndex, ok := numsMap[target-num]; ok {
return []int{preIndex, index}
}
}
return []int{}
}
ps: This question is still relatively simple, if you have a better solution, please leave a message
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。