题目地址
https://leetcode-cn.com/problems/two-sum/
暴力解决
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answerArr = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
answerArr[0] = i;
answerArr[1] = j;
return answerArr;
}
}
}
return null;
}
}
执行用时 61 ms, 内存消耗 41.3 M
使用哈希表
Map<Integer, Integer> map = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int result = target - nums[i];
Integer index = map.get(result);
if (index == null || i == index) {
continue;
}
return new int[]{i, index};
}
return null;
执行用时 3 ms, 内存消耗 41.8 M
官方解法
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
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 new int[0];
执行用时 2 ms, 内存消耗 41.2 M