import java.util.Arrays;
/**
* Created by lihaibin02 on 2016/9/9.
*/
public class findTheMaxInt {
//暴力的解决办法
public int ftmt(int arr[]) {
int max = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1; j++) {
for (int k = j; k < arr.length; k++) {
if (arr[i] == arr[j] + arr[k]) {
if (max < arr[i]) {
max = arr[i];
}
}
}
}
}
return max;
}
//优化的解决办法
/*
* 将数组进行排序,然后从最大的元素向前查找,直到找到满足条件的数,否则返回0
*
* */
public int find_The_Number(int arr[]) {
Arrays.sort(arr);//将arr排序
for (int i = arr.length - 1; i >= 2; i--) {
int left = 0;
int right = i - 1;
while (left < right) {
int temp = arr[left] + arr[right];
if (temp == arr[i]) {
return temp;
} else if (temp < arr[i]) {
left++;
} else if (temp > arr[i]) {
right--;
}
}
}
return 0;
}
public static void main(String[] args) {
findTheMaxInt fTM = new findTheMaxInt();
int arr[] = {1, 10, 3, 4, 6};
System.out.println(fTM.find_The_Number(arr));
}
}
找出集合中最大元素C,满足C=A+B,其中A,B都是集合中的元素
最新推荐文章于 2023-04-10 11:00:47 发布