- 有一个数组{1, 4, 7, 2, 5, 8, 10, 9, 3, 6, 6, 9, 3};
2个数之和12
的元素有几对 , 和匹配的下标- 每个元素只算一次
- 6对
[2,4]
[1,5]
[3,6]
[7,8]
[9,10]
[11,12]
import java.util.*;
public class sum{
public static void main(String[] args){
int[] arr = {1, 4, 7, 2, 5, 8, 10, 9, 3, 6, 6, 9, 3};
int sum = 12;
int count = 0;
//要搜索的对象 map
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
//要匹配的对象 map2
Map<Integer,Integer> map2 = new HashMap<Integer,Integer>();
for(int i = 0 ; i<arr.length ; i++){
int other = sum -arr[i]; // 找other
if(map.containsKey(other)){
count++; // 数次数
map2.put(map.get(other),i);
map.remove(other); //剔除重复项 ,移走与other值一样的
}else{
map.put(arr[i],i);
}
}
System.out.println("对数count = " + count);
System.out.println(map2);
}
}