【发布时间】:2020-01-11 04:44:04
【问题描述】:
给定一个未排序的数组 – arr 找到一对 arr[i] 和 arr[j] 使得
arr[i] < arr[j] & i<j 和 (arr[i] + arr[j]) 是最大值。
预期时间复杂度 - O(n)
对于数组a = {4, 1, 3, 2, 5, 3}
pair is (4, 5).
这是我尝试过的代码..
void findPair(int[] a){
int n = a.length;
int max = a[0];
int secondMax = Integer.MIN_VALUE;
for(int i=1; i<n; i++){
if(a[i]>max){
secondMax = max;
max = a[i];
}
}
if(secondMax == Integer.MIN_VALUE){
System.out.println("-1 -1");
}
else{
System.out.println(secondMax+" "+max);
}
}
【问题讨论】:
-
谢谢。仍然存在:如果没有解决方案,我们返回什么,如
[4,3,2,1]?