Skip to content

Instantly share code, notes, and snippets.

@muromtsev
Created September 23, 2024 21:36
Show Gist options
  • Save muromtsev/ebbcb139b60da53adabe3f24b2fefe9d to your computer and use it in GitHub Desktop.
Save muromtsev/ebbcb139b60da53adabe3f24b2fefe9d to your computer and use it in GitHub Desktop.
Дан отсортированный массив, необходимо вернуть два индекса тех чисел из массива, которые в сумме будут давать target
public class TwoSum {
public static void main(String[] args) {
int[] array = { -9, -6, 0, 1, 2, 7, 11, 15, 20, 35, 47};
System.out.println(Arrays.toString(twoSum(array, 100)));
}
public static int[] twoSum(int[] arr, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(target - arr[i])) {
return new int[]{map.get(target - arr[i]), i};
}
map.put(arr[i], i);
}
return new int[]{};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment