Can I get this problem of Terminated due to time out solved?
I mean how to reduce the complexity or unwanted code in order to solve the issue?
Here is my code:
public class Solution {
public static void main(String[] args) {
int i,n,hit,count=0,p=0,t,tmp,j;
int h[]=new int[100000];
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
hit=sc.nextInt();
t=sc.nextInt();
for(i=0;i<n;i++){
h[i]=sc.nextInt();
}
for(i=0;i<n;i++){
for(j=i;j<n;j++){
if(h[i]>h[j]){
tmp=h[i];
h[i]=h[j];
h[j]=tmp;
}
}
}
for(i=1;i<=t;i++){
h[p]-=hit;
if(h[p]<=0){
count++;
p++;
}
}
System.out.println(count);
}
}
Since I don't know the problem statement, the only thing which I can suggest is to always avoid Bubble Sort . It's complexity is O(n^2)
, and probably that's what hindering you're time requirement.
Use Arrays.sort
like Arrays.sort(h)
The only problem I can see is you need to import the scanner before you can use it. When I ran the code you provided it gave me a timeout because it couldn't locate the scanner, but when I imported the scanner it ran just fine, so I'm assuming that's the same timeout error you're getting. Put this statement at the beginning of your code:
import java.util.Scanner;
The finished code should look like this:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int i,n,hit,count=0,p=0,t,tmp,j;
int h[]=new int[100000];
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
hit=sc.nextInt();
t=sc.nextInt();
for(i=0;i<n;i++){
h[i]=sc.nextInt();
}
for(i=0;i<n;i++){
for(j=i;j<n;j++){
if(h[i]>h[j]){
tmp=h[i];
h[i]=h[j];
h[j]=tmp;
}
}
}
for(i=1;i<=t;i++){
h[p]-=hit;
if(h[p]<=0){
count++;
p++;
}
}
System.out.println(count);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.