实际上我正在尝试解决这个问题hackerrank Missing Numbers
让我为它添加一些描述,实际上有两个数字列表,几乎相同,但因为第一个列表中有一些遗漏,所以第二个列表包含所有完整的数字,而第一个列表缺少其中的一些数字,我们只需打印出第一个列表中丢失的数字。
问题陈述
Numeros,艺术家,拥有两个列表A和B,其中B是A的排列。 Numeros非常自豪这些列表。 不幸的是,在从一个展览到另一个展览的运输过程中,A中的一些数字被遗漏了。你能找到缺失的数字吗?
注意事项
如果数字在列表中出现多次,则必须确保两个列表中该数字的频率相同。 如果不是这种情况,则它也是一个丢失的数字。
您必须按升序打印所有缺失的数字。
仅打印每个缺失的数字一次,即使它丢失了多次也是如此。
B中最大和最小数字之间的差小于或等于100。
输入格式 将有四行输入:
n - the size of the first list
This is followed by n space-separated integers that make up the first list.
m - the size of the second list
This is followed by m space-separated integers that make up the second list.
输出格式 按升序输出缺失的数字:
约束条件
1≤n,m≤1000010
1≤x≤10000,x∈B
Xmax−Xmin<101
示例输入
10
203 204 205 206 207 208 203 204 205 206
13
203 204 204 205 206 207 205 208 203 206 205 206 204
样例输出
204 205 206
我写了这段代码:-
这是代码:-
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Map<Integer, Integer> mA = new HashMap<>(n);
int curr = 0;
while(n--> 0){// Creating the first map having number & its frequency
curr = scan.nextInt();
if(mA.containsKey(curr)){
Integer prev = mA.get(curr);
mA.put(curr, prev + 1);
}else{
mA.put(curr, 1);
}
}
int n1 = scan.nextInt();
Map<Integer, Integer> mB = new HashMap<>(n1);
while(n1--> 0){// Creating the second map having number & its frequency
curr = scan.nextInt();
if(mB.containsKey(curr)){
Integer prev = mB.get(curr);
mB.put(curr, prev + 1);
}else{
mB.put(curr, 1);
}
}
List<Integer> l = new ArrayList<>();
//Problem I think is this part somewhere I am not doing it correct in this loop
for(Map.Entry<Integer, Integer> entry : mB.entrySet()){
Integer k = entry.getKey();
Integer v = entry.getValue();
if(!mA.containsKey(k)){
l.add(k);
}else if(mA.get(k) != v){
l.add(k);
}
}
Collections.sort(l);
List<Integer> list = new ArrayList<>(new LinkedHashSet<Integer>(l));
for(Integer i : l){
System.out.print(i + " ");
}
}
}
我认为问题出在for循环中,我在比较两个map中的条目时。我觉得我没有正确的方式!! 因为它打印了一个在两个地图中具有相同频率计数的数字。