1:将数组中的元素存储在hashmap中,其中key为数组的元素,value为其在数组的下标
2:遍历整个hashmap, 如果hashmap的key中包括(total - curNum),那么说明数组中存在另外一个数满足和当前数相加为total的元素
package com; import jdk.internal.org.objectweb.asm.Handle; import java.util.HashMap; public class shu { public static void main(String[] args) { int[] array={2,3,4,6,7,8,9}; int total=10; TwoS(array,total); } public static void TwoS(int[] array,int total) { if (array==null||array.length<=1) return ; HashMap<Integer,Integer> hashMap=new HashMap<>();//组合数的下标 HashMap<Integer,Integer> valuehashmap=new HashMap<>();//已遍历过的数据 int temp=0; for (int i = 0; i < array.length; i++) { temp=total-array[i]; if (valuehashmap.containsKey(temp)){ hashMap.put(valuehashmap.get(temp),i); continue; } valuehashmap.put(array[i],i); } valuehashmap=null; for (int key:hashMap.keySet()){ System.out.println(array[key]+" "+array[hashMap.get(key)]); } } }