在網上看到過一個面試題,感覺挺有意思,看別人的代碼寫的邏輯不夠謹慎,重寫了一個,較真了又。。。
?
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;}
}
?
版權聲明:本文為博主原創文章,未經博主允許不得轉載。
?