1. Topic
Source of the topic: https://leetcode-cn.com/problems/two-sum
Given an integer array nums
and an integer target value target
, please find the two integers whose sum is the target value in the array, and return their array subscripts.
You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.
You can return answers in any order.
- Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] ==9, return [0, 1].
- Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
- Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
- hint:
2 <= nums.length <= 103
-109 <= nums[i] <= 109
-109 <= target <= 109
There will only be one valid answer
Two, solution
1. The law of violence
- Thought:
As the name suggests, the violence method adopts the method of enumeration to find the numbers nums
that are added one by one target
, and return the subscript of the two numbers after finding it. Here, a double-layer loop method is used.
The brute-force worst-case list needs to be looped n*n
times and costs no extra space, so:
- The time complexity is:
0 ( n 2 ) 0(n^2)0(n2) - The space complexity is:
0 ( 1 ) 0(1)0(1) - the code
func twoSum(nums []int, target int) []int {
//定义数组arr,用来返回结果下标
arr := []int{
}
//双层循环,找到相加为target的两值下标
for i := 0; i < len(nums); i++{
for j := i + 1; j < len(nums); j++{
if nums[i] + nums[j] == target{
//找到后添加到arr数组的尾部
arr = append(arr,i,j)
}
}
}
//返回arr
return arr
}
2. hashmap
- Thought:
The brute force method takes a long time, so you can use the hashmap method to store the value in the key of the hashmap and the subscript in the value. Loop through the array and store the visited value in the hashmap. If target-v
the value of v exists in the hashmap, then we return the subscript of v and hashmap[target-v]
the subscript of v.
The time complexity of finding the value in the hashmap is 0 (1), there are n values in total, and in the worst case, it needs to be checked n times. A hashmap is opened up in space to store n values, so:
- The time complexity is:
0 ( n ) 0(n)0(n) - The space complexity is:
0 ( n ) 0(n)0(n) - the code
func twoSum(nums []int, target int) []int {
//定义hashmap,键为数值,值为下标
hashmap := map[int]int{
}
//遍历nums数组
for i,v := range nums{
//如果存在值为target-v的数,就将其坐标赋给p
//并返回p,i两下标
if p,ok := hashmap[target-v];ok {
return []int{
p,i}
}
//若不存在就将该值和下标放入哈希表
hashmap[v] = i
}
return nil
}