Pairs(hashset的查找应用)

本文深入探讨了大数据开发领域的关键技术,包括Hadoop、Spark、Flink等,并结合实际案例阐述了这些技术在数据处理、分析和存储方面的应用。通过实践操作,读者将能更好地理解大数据开发的核心理念和具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given N integers, count the total pairs of integers that have a difference of K.

Input Format 
The 1st line contains N & K (integers).
The 2nd line contains N numbers of the set. All the N numbers are assured to be distinct.

Output Format
An integer that tells the number of pairs of numbers that have a difference of K.

Constraints:
N <= 105
0 < K < 109
Each integer will be greater than 0 and at least K smaller than 231-1

Sample Input #00:

5 2  
1 5 3 4 2  

Sample Output #00:

3

Sample Input #01:

10 1  
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793 

Sample Output #01:

0
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    static int pairs(int[] a,int k) {
      /* Complete this function */
    	int count  = 0;
		HashSet<Integer> hs = new HashSet<Integer>();
    	for (int i : a) {
			hs.add(i);
		}
    	for (Integer integer : hs) {
			if(hs.contains(integer+k))
			{
				count++;
			}
		}
        return count;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int res;
        
        String n = in.nextLine();
        String[] n_split = n.split(" ");
        
        int _a_size = Integer.parseInt(n_split[0]);
        int _k = Integer.parseInt(n_split[1]);
        
        int[] _a = new int[_a_size];
        int _a_item;
        String next = in.nextLine();
        String[] next_split = next.split(" ");
        
        for(int _a_i = 0; _a_i < _a_size; _a_i++) {
            _a_item = Integer.parseInt(next_split[_a_i]);
            _a[_a_i] = _a_item;
        }
        
        res = pairs(_a,_k);
        System.out.println(res);
    }
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值