整数对查找

题目

请设计一个高效算法,找出数组中两数之和为指定值的所有整数对。
给定一个int数组A和数组大小n以及需查找的和sum,请返回和为sum的整数对的个数。保证数组大小小于等于3000。

测试样例:
[1,2,3,4,5],5,6
返回:2

解答

1.原始暴力解法:复杂度比较高

import java.util.*;

public class FindPair {
    public int countPairs(int[] A, int n, int sum) {
        // write code here
        int count = 0;
        Arrays.sort(A);
        for(int i = 0;i < n;i++){
            for(int j = i + 1;j < n;j++){
                if(A[j] == sum - A[i] ){
                    count++;
                }
            }
        }
        return count;
    }
}

2.使用哈希表
使用哈希表存储对应数字的个数,然后通过getOrDefault(sum-temp,0)方法获得对应数字的个数,最后算出结果。
put方法
V.put(K key, V value)

getOrDefault()方法
V.getOrDefaultt(K key, D defualt) —> return value of key.
当Map集合中有这个key时,就使用这个key值,如果没有就使用默认值defaultValue

import java.util.*;
 
public class FindPair {
    public int countPairs(int[] A, int n, int sum) {
        HashMap<Integer,Integer> map=new HashMap<>();
        int count=0;
        for(int temp:A){
            count+=map.getOrDefault(sum-temp,0);//获得k值
            map.put(temp,map.getOrDefault(temp,0)+1);//保存个数
        }
        return count;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值