有一个数组[1,4,7,2,5,8,10,9,3,6] , 请问两个数之和是12的元素有多少对

  1. 有一个数组{1, 4, 7, 2, 5, 8, 10, 9, 3, 6, 6, 9, 3};
  2. 2个数之和12的元素有几对 , 和匹配的下标
  3. 每个元素只算一次
  4. 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);
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值