Likou brush question record vol.1 - the sum of two numbers

topic:

Solution 1: Violent traversal

 Two-layer loop, directly traversing to find whether there are two numbers whose sum is the target in the array, if it exists, output two subscripts, if not, output an empty set;

-------------------------------------------------------------------------------------------------------------------------------- 

 Solution 2: Hash table

The time complexity of the brute force solution is concentrated in  target - x the process of finding the position. Therefore, we need a better method that can quickly find whether the target element exists in the array. If it exists, we need to find out its index.

target - x Using a hash table, the time complexity of finding can  be reduced from O(N) to O(1).

First create a hash table and start traversing the array. If it is not found in the hash table, target - x it will x be inserted into the hash table, and if it is found, the corresponding subscript value will be output.

The advantage of this is target - x一定会出现在x值之后,因为算法再插入前就已经在x之前的值中寻找过target - x that it also avoids the solution that matches itself with repeated numbers. 

Guess you like

Origin blog.csdn.net/HimaRe1/article/details/130977212