题目描述

题解
// 暴力法
// 执行用时:11 ms, 在所有 Java 提交中击败了7.82%的用户
// 内存消耗:38.6 MB, 在所有 Java 提交中击败了57.34%的用户
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2]
for (int left = 0
int com = target - nums[left]
for (int right = left + 1
if (nums[right] == com) {
res[0] = left
res[1] = right
break
}
}
}
return res
}
}
// 哈希表法
// 每次遍历就查看当前值的target - nums[i]是不是在map中的key,
// 每次遍历就以<值,索引>形式放进map中。
// 执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
// 内存消耗:38.6 MB, 在所有 Java 提交中击败了64.99%的用户
import java.util.HashMap
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2]
HashMap<Integer, Integer> map = new HashMap<>()
for (int i = 0
if (map.containsKey(target - nums[i]) {
return new int[]{map.get(target - nums[i]), i}
}
map.put(nums[i], i)
}
return new int[0]
}
}