决心把leetcdoe从头做一遍, 就从 two sum 开始吧
本题的提意思非常直观,简单说一下
给了一个数组 nums 和 target, 找出数组的index 使其值的和等于target
Eg. nums = [2, 7, 11, 15], target = 9;
return [0, 1] (因为nums[0] + nums[1] = 9)
本题最直接的方法是用brute force来做,用两个for loop 从头到尾遍历一遍
public int[] twoSumBruteForce(int[] nums, int target) {
if (nums == null || nums.length < 2) {
throw new IllegalArgumentException("argument is not valid");
}
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
throw new RuntimeException("index not found");
}
我们也可以用 Hashmap 来做
遍历数组
key存当前的数组的值
value存当前数组的index
如果target - nums[i] 在map中存在key
说明我们找到了目标index
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length < 2) {
throw new IllegalArgumentException("argument is not valid");
}
HashMap map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[] {map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
throw new RuntimeException("index not found");
}