举例
给出单调递增数组[1,2,3,4,5]和目标值6,数组中 1+5=6,2+4=6,但是15<24,所以返回1和5
public Integer[] findTwoSumEqualTarget(Integer[] arr, Integer target) {
if (arr == null) {
return null;
}
int head = 0;
int tail = arr.length - 1;
int min = Integer.MAX_VALUE;
Integer first = 0;
Integer second = 0;
while (head < tail) {
if (arr[head] + arr[tail] < target) {
head++;
} else if (arr[head] + arr[tail] > target) {
tail--;
} else {
if (arr[head] * arr[tail] < min) {
first = head;
second = tail;
min = arr[first] * arr[second];
}
head++;
tail--;
}
}
return new Integer[]{arr[first], arr[second]};
}
网友评论