Two Sum
Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
1
2
| Example:
Given nums = [2, 7, 11, 15], target = 9,
|
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
假定只有唯一解的情况下在数组中找出和为target
的两个数
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| func twoSum(nums []int, target int) []int {
res := make([]int, 2)
m := map[int]int{}
for i := range nums {
m[target - nums[i]] = i
}
for i := range nums {
idx, ok := m[nums[i]]
if ok {
if i == idx {
continue
}
res[0] = idx
res[1] = i
sort.Ints(res)
break
}
continue
}
return res
}
|
Similar Problem