「力扣」第 1 题:“两数之和”代码
方法一:暴力解法
Java 代码:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
方法二:使用查找表
Java 代码:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
Map<Integer, Integer> hashMap = new HashMap<>(len - 1);
hashMap.put(nums[0], 0);
for (int i = 1; i < len; i++) {
int another = target - nums[i];
if (hashMap.containsKey(another)) {
return new int[]{i, hashMap.get(another)};
}
hashMap.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}