力扣 - 1. 两数之和
题目
思路1(暴力枚举)
- 遍历数组
- 在每次遍历时,记录下target减去当前数组的值为temp
- 再从当前位置开始的后一个(因为同一个元素不能遍历两次)元素开始遍历到结束,如果和temp值相等,那么就将i和j的索引值记录到res中,返回res即可
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
int temp = target - nums[i];
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == temp) {
res[0] = i;
res[1] = j;
return res;
}
}
}
return null;
}
}
复杂度分析
- 时间复杂度:\(O(N^2)\),其中 N 为数组长度。
- 空间复杂度:\(O(1)\)
思路2(哈希表)
- 使用暴力的话是将计算出另一个值,在剩下的数组中遍历查找,这样时间复杂度很慢
- 我们考研使用哈希表,将遍历过的值存到哈希表中,然后每次从哈希表中查找另一个值,找到了就说明存在,而且复杂度仅仅为\(O(1)\)
代码
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> hashtable = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (hashtable.containsKey(target - nums[i])) {
return new int[] {hashtable.get(target-nums[i]), i};
}
hashtable.put(nums[i], i);
}
return null;
}
}
复杂度分析
- 时间复杂度:\(O(N)\),其中 N 为数组长度
- 空间复杂度:\(O(N)\),其中 N 为数组长度
我走得很慢,但我从不后退!

浙公网安备 33010602011771号