技术:javascript
此题为Leetcode上的题目,本文采用简单二叉树深度遍历的方式实现。在数据量庞大的情况下,可以将简单二叉树进一步优化成平衡二叉树。
function Node(value, index) {
this.left = null
this.right = null
this.value = value
this.index = index
}
// 创建链表
function createLinkedList(arr) {
if (arr.length === 0) return null
var root = new Node(arr[0], 0)
var node = root
for (let i = 1; i <= arr.length; i++) {
if (i === arr.length) {
node.next = null
} else {
node.next = new Node(arr[i], i)
node = node.next
}
}
return root
}
function addNode(root, nextValue, index) {
if (root === null) return null
if (root.value <= nextValue) {
if (root.right === null) root.right = new Node(nextValue, index)
else addNode(root.right, nextValue, index)
} else {
if (root.left === null) root.left = new Node(nextValue, index)
else addNode(root.left, nextValue, index)
}
}
// 构建二叉搜索树
function createTree(arr) {
if (arr === null || arr.length === 0) return null
var root = new Node(arr[0], 0)
for (let i = 1; i < arr.length; i++) {
addNode(root, arr[i], i)
}
return root
}
function deepSearch(root, differenceVal, fistNode) {
if (root === null) return false
if (root.value === differenceVal && root.index !== fistNode.index) return root
if (root.value > differenceVal) {
return deepSearch(root.left, differenceVal, fistNode)
} else {
return deepSearch(root.right, differenceVal, fistNode)
}
}
function goThrough(link, tree, sum) {
if (link === null) return false
var differenceVal = sum - link.value // 深度搜索查找差值
if (!deepSearch(tree, differenceVal, link)) { // 第三个参数可以直接使用link.index作为入参
return goThrough(link.next, tree, sum)
} else return {
firstIndex: link.index,
secondIndex: deepSearch(tree, differenceVal, link).index
}
}
function twoSum(arr, sum) {
var tree = createTree(arr)
var link = createLinkedList(arr)
let result = goThrough(link, tree, sum)
console.log('result', result);
}
console.time()
let arr = [44, 6, 22, 56, 12, 3, 5, 3, 300, 100, 56, 12, 3, 5, 3, 300, 100]
console.log(arr.length);
twoSum(arr, 400)
console.timeEnd();