在网上看到过一个面试题,感觉挺有意思,看别人的代码写的逻辑不够谨慎,重写了一个,较真了又。。。
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;
}
}
精简代码:优化数组元素求和算法

本文深入探讨并优化了一款用于查找数组中和等于特定值的元素的算法,通过增加溢出检查和边界条件处理,提高了代码健壮性和效率。详细介绍了算法改进的步骤和实现细节。

430

被折叠的 条评论
为什么被折叠?



