题目
题解
暴力枚举:
两个for循环遍历
class DoubleNumSum {
public int[] twoSum(int[] nums, int target) {
int len = nums.length, i, j = 0;
for (i = 0; i < len; i++) {
for (j = i + 1; j < len; j++) {
if (nums[i] + nums[j] == goal) {
return new int[]{i, j};
}
}
}
return null;
}
}
Hash:
性能优越
class Solution {
public int[] twoSum(int[] nums, int target) {
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];
}
}