算法优化技巧与实践
1. 利用哈希表优化查找
在编程中,我们常常会遇到需要查找数组中是否存在两个数之和等于某个特定值的问题。比如要判断数组中是否有两个数相加等于 10。下面是一段相关代码:
for(let i = 0; i < array.length; i++) {
// Check if the hash table contains a key which, when added
// to the current number, would add up to 10:
if(hashTable[10 - array[i]]) {
return true;
}
// Store each number as a key in the hash table:
hashTable[array[i]] = true;
}
// Return false if we get to the end of the array without
// finding any number's counterpart:
return false;
这段代码的核心思路是遍历数组,对于每个元素,检查哈希表中是否存在与之相加等于 10 的数。如果存在,就返回 true ;如果遍历完数组都没找到,就返回 false 。同时,在遍历过程中,将每个元素作为键存入哈希表。这样做的好处是,利用哈希表的 O(1) 查找特性,将算法的时间复杂度从原本可能的 O(N^2) 降低到了 O(N)。 </
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



