leetcode 1. Two Sum
审题:
只有一种组合的解决方案
同一元素不能使用2次
解法:
- Brute Force
- Two-pass Hash Table
- One-pass Hash Table
1. 遍历2次数组,寻找满足条件的元素下标
func twoSum(nums []int, target int) (result []int) {
for index, num := range nums {
for sIndex, sNum := range nums {
if num+sNum == target && index != sIndex {
result = []int{index, sIndex}
return
}
}
}
return
}
2. Two-pass Hash Table
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, v := range nums {
m[v] = i
}
for i, v := range nums {
result := target - v
if index, ok := m[result]; ok && index != i {
return []int{i, index}
}
}
return nil
}
3. One-pass Hash Table
func twoSum(nums []int, target int) []int {
m := make(map[int]int)
for i, n := range nums {
if index, ok := m[n]; ok && index != i {
return []int{index, i}
} else {
// amazing!!!
m[target-n] = i
}
}
return nil
}
- 原文作者:zhutou
- 原文链接:https://flygar.org/2020/03/22/leetcode-1.html
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。