[LeetCode][1. 两数之和] 2种方法:暴力 和 HashMap
By Long Luo
1. 两数之和 题解。
方法一:暴力枚举
思路及算法:
最容易想到的方法是使用两层循环,第一层循环枚举数组中的每一个数
JAVA
1 | public int[] twoSum(int[] nums, int target) { |
复杂度分析
- 时间复杂度:
,其中 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。 - 空间复杂度:
。
方法二:哈希表
思路及算法:
方法一的时间复杂度较高的原因是寻找
使用
这样我们创建一个哈希表,对于每一个
JAVA
1 | public static int[] twoSum(int[] nums, int target) { |
复杂度分析
- 时间复杂度:
,其中 是数组中的元素数量。对于每一个元素 ,我们可以 地寻找 。 - 空间复杂度:
,其中 是数组中的元素数量。主要为哈希表的开销。
All suggestions are welcome. If you have any query or suggestion please comment below. Please upvote👍 if you like💗 it. Thank you:-)
Explore More Leetcode Solutions. 😉😃💗
预览: