我怎样才能减少这个程序的时间复杂度?
How can i reduce the time complexity of this program?
此程序在 list
中取 n
个整数,然后给出用户输入的下一个 t
个数字的 count
。如果数字在列表中,则它 prints the count
,如果不在,则它给出 "NOT PRESENT"
消息。我想知道我是否可以 reduce its time and space
复杂性,或者我是否必须对程序采取另一种方法。
import java.util.*;
class Memorise_Me
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
List<Integer> list=new ArrayList<Integer>(n);
while(n>0)
{
list.add(sc.nextInt());
n--;
}
int t=sc.nextInt();
int x,count=0;
while(t>0)
{
x=sc.nextInt();
count=Collections.frequency(list,x);
if(count==0)
System.out.println("NOT PRESENT");
else
System.out.println(count);
t--;
}
sc.close();
}
这段代码所做的几乎所有工作都是组织输入和输出,除了这一行:count=Collections.frequency(list,x);
这是唯一发生实际计算的行。实际上,是时候了,space 复杂性是由标准 java.util.Collections.frequency 方法决定的,对于这种微不足道的情况,它应该具有相当好的时间和 space 特性。
此程序在 list
中取 n
个整数,然后给出用户输入的下一个 t
个数字的 count
。如果数字在列表中,则它 prints the count
,如果不在,则它给出 "NOT PRESENT"
消息。我想知道我是否可以 reduce its time and space
复杂性,或者我是否必须对程序采取另一种方法。
import java.util.*;
class Memorise_Me
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
List<Integer> list=new ArrayList<Integer>(n);
while(n>0)
{
list.add(sc.nextInt());
n--;
}
int t=sc.nextInt();
int x,count=0;
while(t>0)
{
x=sc.nextInt();
count=Collections.frequency(list,x);
if(count==0)
System.out.println("NOT PRESENT");
else
System.out.println(count);
t--;
}
sc.close();
}
这段代码所做的几乎所有工作都是组织输入和输出,除了这一行:count=Collections.frequency(list,x);
这是唯一发生实际计算的行。实际上,是时候了,space 复杂性是由标准 java.util.Collections.frequency 方法决定的,对于这种微不足道的情况,它应该具有相当好的时间和 space 特性。