两数之和 (twoSum)
2024年11月12日小于 1 分钟约 55 字...
两数之和 (twoSum)
https://leetcode.cn/problems/two-sum/
解法思路
用 target 挨个 减去 nums 中的项,然后得出结果,如果结果 nums 中存在,则记录下标
Golang
package main
import (
"fmt"
)
func main() {
nums := []int{
3, 2, 4,
}
target := 6
results := twoSum(nums, target)
fmt.Println("results", results)
results2 := twoSum2(nums, target)
fmt.Println("results2", results2)
}
// 暴力求解
func twoSum(nums []int, target int) []int {
returnVal := []int{}
for k1, v1 := range nums {
diff := target - v1
for k2, v2 := range nums {
if diff == v2 && k2 != k1 {
returnVal = append(returnVal, k2)
}
}
}
return returnVal
}
// 利用哈希 map
func twoSum2(nums []int, target int) []int {
hashTable := map[int]int{}
for i, x := range nums {
p, ok := hashTable[target-x]
if ok {
return []int{p, i}
}
hashTable[x] = i
}
return nil
}
JavaScript
// 暴力求解
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
const el = nums[i];
const diff = target - el;
const idxOf = nums.indexOf(diff);
if (idxOf > -1 && idxOf != i) {
return [i, idxOf];
}
}
return;
};
// 利用哈希map
var twoSum2 = function (nums, target) {
var map = {};
for (let i = 0; i < nums.length; i++) {
const el = nums[i];
const res = map[target - el];
if (res !== undefined) {
return [res, i];
}
map[el] = i;
}
return;
};
// 代码执行块
(function () {
const nums = [2, 7, 11, 15];
const target = 9;
// const result = twoSum(nums, target);
// console.log('result', result);
const result2 = twoSum2(nums, target);
console.log('result2', result2);
})();
你认为这篇文章怎么样?
- 0
- 0
- 0
- 0
- 0
- 0