今日头条笔试第一题求解
import java.util.*;
public class Main{
public static void main(String[] args) {
int n,k;
Scanner scanner=new Scanner(System.in);
n=scanner.nextInt();
k=scanner.nextInt();
Set<Integer> hashSet=new HashSet<>();
int temp;
int cnt=0;
for (int i=0;i<n;i++) {
temp=scanner.nextInt();
if (hashSet.contains(temp))
continue;
else{
hashSet.add(temp);
if (hashSet.contains(temp-k))
cnt++;
if (k!=0&&hashSet.contains(temp+k))
cnt++;
}
}
System.out.println(cnt);
}
}
请问这个算法的问题出在哪?超时了。
另外如果有大牛可以发布一下ac的解法就感激不尽啦

查看10道真题和解析