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

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

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;
	}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/liushijie/p/4712920.html