暴力解法
class Solution {
public int[] twoSum(int[] nums, int target) {
int a = 0;
int b = 0;
for (int i = 0; i < nums.length; i++) {
a = nums[i];
for (int j = i + 1; j < nums.length; j++) {
b = nums[j];
if (a + b == target) {
//这种输出方便一些 小括号是大小 大括号才是数
return new int[] { i, j };
}
}
}
return nums;
}
}
哈希表
public static int[] twoSum2(int[] nums, int target) {
int len=nums.length;
Map<Integer, Integer> hashMap=new HashMap<Integer, Integer>(len);
hashMap.put(nums[0], 0);
for (int i = 1; i < nums.length; i++) {
int another=target-nums[i];
if (hashMap.containsKey(another)) {
return new int[] {i,hashMap.get(another)};
}
hashMap.put(nums[i], i);
}
return null;
}
效率确实高好多,不过一般人第一眼,应该还是用for循环吧。毕竟方便