题解 | #和为S的两个数字#
和为S的两个数字
http://www.nowcoder.com/practice/390da4f7a00f44bea7c2f3d19491311b
离大谱解法,单独处理多对的情况
import java.util.*; public class Solution { public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) { int n = array.length; ArrayList<Integer> ans = new ArrayList<Integer>(); Map<Integer,Integer> map = new HashMap<>(); for(int i = 0;i < n;i++){ if(map.containsKey(sum-array[i])){ ans.add(sum-array[i]); ans.add(array[i]); } map.put(array[i],i); } int min = Integer.MAX_VALUE,index = 0,index1 = 1; if(ans.size() > 2){ for(int i = 0;i < ans.size()-1;i+=2){ if(ans.get(i)*ans.get(i+1) < min){ min = ans.get(i)*ans.get(i+1); index = i; index1 = i+1; } } ArrayList<Integer> res = new ArrayList<Integer>(); res.add(ans.get(index)); res.add(ans.get(index1)); return res; } return ans; } }