/** * 题目: * 输入一个递增排序的数组和一个数字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); } }
剑指offer:和位s的两个数字(java)
最新推荐文章于 2020-06-21 23:23:25 发布