Created
September 23, 2024 21:36
-
-
Save muromtsev/ebbcb139b60da53adabe3f24b2fefe9d to your computer and use it in GitHub Desktop.
Дан отсортированный массив, необходимо вернуть два индекса тех чисел из массива, которые в сумме будут давать target
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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