您的位置:首页 > 其它

给定一个值S,在有序数组中找出两个元素A和B,使 A+B = S.

2014-10-10 21:06 459 查看
在网上看到过一个面试题,感觉挺有意思,看别人的代码写的逻辑不够谨慎,重写了一个,较真了又。。。

package com.array7.algorithm;

public class AlgorithmTest {
public static void main(String[] args) {
int[] arr = {2 ,4 ,5 ,8 ,10 ,12 ,13 ,16 ,17,Integer.MAX_VALUE };
int sum = 13;
String result = getSumElements(arr,sum);
System.out.println(result);

int[] arr2 = {-21 ,-20 ,-15 ,-4 ,-1 ,0 , 2, 13 ,16 ,17,Integer.MAX_VALUE };
int sum2 = -13;
result = getSumElements(arr2,sum2);
System.out.println(result);
}

public static String getSumElements(final int[] arr, final int sum) {
if (arr == null || arr.length < 2) {
throw new IllegalArgumentException("参数不合法...");
}

int min = 0;
int max = arr.length - 1;
long tempSum = 0L;
String result = "not found";
while (min < max) {
tempSum = new Long(arr[min]) + new Long(arr[max]);	// 防止数值溢出,保证数据健壮性
if (tempSum > sum) {
max--;
} else if (tempSum < sum) {
min++;
} else {
result = arr[min] + "," + arr[max];
break;
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐