Last active
December 15, 2019 13:33
-
-
Save steklopod/739cb9940d63ad9d27a30938814e682f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import org.junit.jupiter.api.Test; | |
import org.junit.jupiter.api.TestInstance; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.List; | |
import static org.junit.jupiter.api.Assertions.assertEquals; | |
// Написать функцию, которая получает на вход массив и искомое число и возвращает 2 элемента в массиве, которые в сумме дадут это число (за n^2 решать не надо). | |
public class Яндекс_2 { | |
private List<Integer> arr = Arrays.asList(1, 11, 2, 40, 3); | |
@Test | |
void find() { | |
Pair pair = найтиПаруЧиселВСуммеДастИскомоеЧисло(arr, 5); | |
assertEquals(2, pair.left, "Первый элемент [arr], который в сумме даст 5"); | |
assertEquals(3, pair.right, "Второй элемент [arr], который в сумме даст 5"); | |
} | |
private Pair найтиПаруЧиселВСуммеДастИскомоеЧисло(List<Integer> arr, int expectedSum) { | |
Collections.sort(arr); | |
int left = 0; | |
int right = arr.size() - 1; | |
while (left != right) { | |
int summ = arr.get(left) + arr.get(right); | |
if (summ < expectedSum) left++; | |
else if (summ > expectedSum) right--; | |
else return new Pair(arr.get(left), arr.get(right)); | |
} | |
return new Pair(-1, -1); | |
} | |
static class Pair { | |
int left; | |
int right; | |
public Pair(int left, int right) { | |
this.left = left; | |
this.right = right; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment