我编写了一个代码,它采用两个整数数组作为输入,并创建两个树形图及其频率(整数出现的次数),并写入两个中都不存在的值,或者频率不同,当测试用例失败时由于 TLE(超出时间限制),数组大小为 10^6。
import java.util.*;
//import java.util.stream.Collectors;
public class Solution {
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int x=s.nextInt();
int[] arr=new int[x];
int i,j,count=0;
for(i=0;i<x;i++)
{
arr[i]=s.nextInt();
}
Map<Integer, Integer> check=new TreeMap<Integer, Integer>();
for(i=0;i<x;i++)
{
for(j=0;j<x;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
check.put(arr[i], count);
count=0;
}
int y=s.nextInt();
int[] brr=new int[y];
for(i=0;i<y;i++)
{
brr[i]=s.nextInt();
}
Map<Integer, Integer> check1=new TreeMap<Integer, Integer>();
int count1=0;
for(i=0;i<y;i++)
{
for(j=0;j<y;j++)
{
if(brr[i]==brr[j])
{
count1++;
}
}
check1.put(brr[i], count1);
count1=0;
}
//System.out.println(check);
//System.out.println(check1);
ArrayList<Integer> store=new ArrayList<Integer>();
for(int key:check1.keySet())
{
if(check.containsKey(key))
{
int valb=check.get(key);
int vala=check1.get(key);
if(vala-valb!=0)
{
store.add(key);
}
}
else
{
store.add(key);
}
}
//Collections.sort(store);
for(i=0;i<store.size();i++)
{
System.out.print(store.get(i)+" ");
}
}
}
最佳答案
不要像这样在嵌套循环中遍历同一数组(O(n^2) 时间)计算重复项
for(i=0;i<x;i++)
{
for(j=0;j<x;j++)
{
if(arr[i]==arr[j])
{
count++;
}
}
check.put(arr[i], count);
count=0;
}
您可以为数组中的每个数字增加映射值。像这样的事情:
for (int item: arr) {
if (check.containsKey(item)) {
check.put(item, check.get(item) + 1);
} else {
check.put(item, 1);
}
}
最后,这会生成一个映射,其中每个键都是数组中的一个数字,键的每个值都是该数字在数组中出现次数的计数器。例如对于数组
[1, 2, 3, 4, 2, 3, 4, 5]
map 看起来像
{1 -> 1, 2 -> 2, 3 -> 2, 4 -> 2, 5 -> 1}
如果您使用 HashMap 而不是 TreeMap,这也会在 O(n) 时间内运行。
要对输出进行排序,您可以使用 TreeSet 而不是 ArrayList。
关于java - 在java上通过TLE的代码优化建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55265430/