今日头条春招第一题

题目描述:

在n个元素的数组中,找到差值为k的数字对去重后的个数。
输入描述:

第一行,n和k,n表示数字个数,k表示差值
第二行,n个正整数
输出描述:

差值为k的数字对去重后的个数
样例

in:
5 2
1 5 3 4 2
out:
3

思路:

使用set存储,去重
排序 遍历查找/二分查找
使用set.contains函数查找是否存在

 1 import java.util.*;
 2 public class Toutiao1 {
 3 
 4     public static void main(String[] args) {
 5         // TODO Auto-generated method stub
 6         Scanner sc = new Scanner(System.in);
 7         int n = sc.nextInt();
 8         int k = sc.nextInt();
 9         int ans = 0;
10         int[] a = new int[n];
11         List<Integer> numList = new ArrayList<Integer>();
12         for(int i = 0; i <n;i++){
13             a[i]=sc.nextInt();
14             numList.add(a[i]);
15         }
16         TreeSet<Integer> hset = new TreeSet<Integer>();
17         hset.addAll(numList);
18         Iterator<Integer> i = hset.iterator();
19         while(i.hasNext()){
20             Integer integer =  i.next();
21             if(hset.contains(integer+k)){
22                 ans++;
23             }
24         }
25         System.out.println(ans);
26     }
27 
28 }

 

转载于:https://www.cnblogs.com/zlz099/p/8649561.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值