Для классической задачи Leetcode TwoSum: для заданного массива целых чисел вернуть индексы двух чисел так, чтобы они складывались до определенной цели.
Можно предположить, что каждый вход будет иметь только одно решение, и вы не можете использовать один и тот же элемент дважды.
Пример:
Учитывая nums = [2, 7, 11, 15], target = 9, потому что nums [0] + nums [1] = 2 + 7 = 9, верните [0, 1].
пробный код ниже, он пройдет тестовые случаи, но не получится для отправки.
public class Solution {
public int[] twoSum (int[] arr, int target) {
if (arr == null || arr.length < 1) {
throw new IllegalArgumentException ("array given is null or
length less than 1, no two sum solutions");
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
map.put (arr[i], i);
int component = target -arr[i];
if (map.containsKey(component) && map.get(component) != i) {
return new int[] {i, map.get(component)};
}
}
throw new IllegalArgumentException (" no two sum solution found
");
}
}
Хотя, если я простопереместите map.put после того, как проверка решения, как показано ниже, пройдет, не можете понять, почему?
public class Solution {
public int[] twoSum (int[] arr, int target) {
if (arr == null || arr.length < 1) {
throw new IllegalArgumentException ("array given is null or
length less than 1, no two sum solutions");
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
int component = target -arr[i];
if (map.containsKey(component) && map.get(component) != i) {
return new int[] {i, map.get(component)};
}
map.put (arr[i], i);
}
throw new IllegalArgumentException (" no two sum solution found
");
}
}