劍指offer:和位s的兩個數字(java)
阿新 • • 發佈:2018-12-12
/** * 題目: * 輸入一個遞增排序的陣列和一個數字S,在陣列中查詢兩個數,使得他們的和正好是S, * 如果有多對數字的和等於S,輸出兩個數的乘積最小的 * 解題思路: * 具體見程式碼 */ import java.util.ArrayList; public class P280_FindNumsWithSumS { public ArrayList<Integer> FindNumsWithSumS(int[] array,int sum) { ArrayList<Integer> result = new ArrayList<>(); if (array == null || array.length == 0) { return result; } for (int i = 0, j = array.length - 1; i < j; ) { if (array[i] + array[j] == sum) { result.add(array[i]); result.add(array[j]); break; } else if (array[i] + array[j] > sum) { j--; } else if (array[i] + array[j] < sum) { i++; } } return result; } public static void main(String[] args) { int[] array = {1, 2, 4, 7, 11, 15}; int sum = 15; P280_FindNumsWithSumS test = new P280_FindNumsWithSumS(); ArrayList<Integer> result = test.FindNumsWithSumS(array, sum); System.out.println(result); } }