1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class Main { public static int[] findNumbers(int[] numbers, int target) { int pLeft = 0; int pRight = numbers.length - 1;
while (pLeft < pRight) { int sum = numbers[pLeft] + numbers[pRight]; if (sum == target) { return new int[]{numbers[pLeft], numbers[pRight]}; } else if (sum < target) { pLeft++; } else { pRight--; } }
return new int[]{-1, -1}; }
public static void main(String[] args) { int[] results = findNumbers(new int[]{2, 4, 5, 6, 12}, 10); System.out.printf("[%d, %d]%n", results[0], results[1]);
results = findNumbers(new int[]{2, 4, 5, 6, 12}, 3); System.out.printf("[%d, %d]%n", results[0], results[1]); } }
|