这是我的在线面试问题,我已经提交了答案。但是,编译因时间而终止,所以我刚刚提交。我可以收到你的反馈意见吗?提前谢谢。
问题:
给定N个数,[N <= 10 ^ 5]我们需要计算具有差异的总数对K
输入格式:
输出格式:
示例输入#00:
5 2
1 5 3 4 2
示例输出#00:
3
我的代码:
import java.io.*
import java.util.*;
public class DiffNumbers {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line1 = in.readLine();
String line2 = in.readLine();
int n = Integer.parseInt(line1.split(" ")[0]);
int diff = Integer.parseInt(line1.split(" ")[1]);
Hashtable table = new Hashtable();
int[] arr = new int[n];
for(in i=0; i<n; i++) {
arr[i] = Integer.parseInt(line2.split(" ")[i]);
table.put(Integer.parseInt(line2.split(" ")[i]));
}
int count = 0;
for(in i=0; i<n; i++) {
if(table.containsKey(arr[i]+diff) {
count++;
}
}
system.out.println(count);
}
}
答案 0 :(得分:0)
使用HashMap / Table需要额外的空间。如果你想避免它,你可以这样做
1)对数组进行排序
2)将outputCount初始化为0
3)让我们有两个指针。 &#34;第一&#34;从0开始,&#34;其他&#34;指针以1开头。
4)
while(arr[other]-arr[first] <requiredDifference)
other ++;
if(arr[other]-arr[first] == requiredDifference)
outputCount++;
else // no match for arr[first]
first++;
5)
return outputCount;
解释: - 当差异超过需求差异时,你就会停止前进&#34;其他&#34; poiner。所以arr [first]没有匹配。所以先行前进。现在为新的arr [first]做同样的逻辑。这次你将继续检查&#34;其他&#34;的当前位置。数组排序;较低的号码不会有必要的匹配。
答案 1 :(得分:0)
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line1 = in.readLine();
String line2 = in.readLine();
int diff = Integer.parseInt(line1.split(" ")[1]);
Map<Integer, Object> nMap = new HashMap<Integer, Object>();
Map<Integer, Boolean> uMap = new HashMap<Integer, Boolean>();
Map<Integer, Boolean> lMap = new HashMap<Integer, Boolean>();
String[] numbers = line2.split(" ");
//init maps
for(String number : numbers){
Integer intValue = Integer.valueOf(number);
nMap.put(intValue, new Object()); //original set, N
uMap.put(intValue + diff, false); //upper-bound map
lMap.put(intValue - diff, false); //lower-bound map
}
int count = 0;
for(Integer nKey : nMap.keySet()){
//Do if the lower-bound of n exists in N and if n hasn't used as an upper-bound?
if(nMap.get(nKey - diff) != null && !uMap.get(nKey)){
count++;
//Mark the lower-bound as used.
lMap.put(nKey - diff, true);
}
//Do if the upper-bound of n exists in N and if n hasn't used as an lower-bound?
if(nMap.get(nKey + diff) != null && !lMap.get(nKey)){
count++;
//Mark the upper-bound as used.
uMap.put(nKey + diff, true);
}
}
System.out.println(count);
}
答案 2 :(得分:-3)
没有太多理由将整数存储在数组和哈希表中。我们可以修改您的代码,以便在单个for循环中完成所有工作。
for(int i=0; i<n; i++) {
int j = Integer.parseInt(line2.split(" ")[i]) //probably not how I would go about this
table.put(j);
if(table.containsKey(j+diff)) {
count++;
}
if(table.containsKey(j-diff)) {
count++;
}
}