Optimize the given Solution without changing the logic of the program. Also calculate the Time Complexity

huangapple go评论79阅读模式
英文:

Optimize the given Solution without changing the logic of the program. Also calculate the Time Complexity

问题

这是一个GFG练习问题因此不能配置编译器

问题
给定一个正整数数组你的任务是找出数组中的"领袖"
注意如果数组中的元素大于等于其右侧的所有元素则称其为领袖同时最右侧的元素总是领袖

输入
输入的第一行包含一个整数T表示测试用例的数量接下来是T个测试用例的描述
每个测试用例的第一行包含一个整数N表示数组的大小
第二行包含N个用空格分隔的正整数表示数组的元素

输出
输出所有的领袖

约束
1 <= T <= 100
1 <= N <= 10^7
0 <= Ai <= 10^7

我的解决方案

import java.util.*;
import java.io.*;
import java.lang.*;
public class Main
{  
    static BufferedReader z1 = new BufferedReader(new InputStreamReader(System.in));
      public static void main (String[] args)throws Exception
    {    
        int T=Integer.parseInt(z1.readLine());
		 while(T-- > 0)
		{      
              int N=Integer.parseInt(z1.readLine());
           solution ob = new solution();
		      int []a=new int[N];
		      a=ob.input(N,z1);
		      int x=0;
		      ob.leader(a,N,x);
		}
    }
}
class solution
{  
    static int[] input(int N, BufferedReader z1)throws Exception
   {    
         int a[]=new int[N];
          String s=z1.readLine();
          String []str=s.split(" ");
		  /* for(int y=0;y<N;y++)
		     a[y]=Integer.parseInt(str[y]); */
		  toInts(str,a,0);
            return a;
   } 
    
    static void toInts(String[] strings, int[] ints, int start) {
    if (start > strings.length - 1) {
        return;
    }
    ints[start] = Integer.parseInt(strings[start]);
    toInts(strings, ints, start+1);
}

    static void leader(int []a,int N,int x)
   {    
           int count = 0;
           if(x==N-1)
            System.out.println(a[x]);
            else
            { 
               count = compare(a,x,x+1,count,N);
	         /* for(int y=x+1;y<N;y++)
	           if(a[x]>=a[y])
	             count++; */
	           if(count==(N-x-1))
	             System.out.print(a[x]);
	           leader(a,N,x+1);
            }
	}
	static int compare(int []a,int x,int y,int count,int N)
	{
	    if(y==N)
	     return count;
	    else
	    {
	        if(a[x]>=a[y])
	         count ++;
	        return compare(a,x,y+1,count,N);
	    }
	}
}
错误

运行时错误
运行时错误超出时间限制

你的程序执行时间超过了预期的时间限制预期时间限制为3.00秒
英文:

This is a GFG practice problem hence compiler cannot be configured

Question
Given an array of positive integers. Your task is to find the leaders in the array.
Note: An element of array is leader if it is greater than or equal to all the elements to its right side. Also, the rightmost element is always a leader.

Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N denoting the size of array.
The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.

Output:
Print all the leaders.

Constraints:<br>
1 <= T <= 100<br>
1 <= N <= 107<br>
0 <= Ai <= 107<br>

My Solution :

import java.util.*;
import java.io.*;
import java.lang.*;
public class Main
{  
static BufferedReader z1 = new BufferedReader(new InputStreamReader(System.in));
public static void main (String[] args)throws Exception
{    
int T=Integer.parseInt(z1.readLine());
while(T-- &gt; 0)
{      
int N=Integer.parseInt(z1.readLine());
solution ob = new solution();
int []a=new int[N];
a=ob.input(N,z1);
int x=0;
ob.leader(a,N,x);
}
}
}
class solution
{  
static int[] input(int N, BufferedReader z1)throws Exception
{    
int a[]=new int[N];
String s=z1.readLine();
String []str=s.split(&quot; &quot;);
/* for(int y=0;y&lt;N;y++)
a[y]=Integer.parseInt(str[y]); */
toInts(str,a,0);
return a;
} 
static void toInts(String[] strings, int[] ints, int start) {
if (start &gt; strings.length - 1) {
return;
}
ints[start] = Integer.parseInt(strings[start]);
toInts(strings, ints, start+1);
}
static void leader(int []a,int N,int x)
{    
int count = 0;
if(x==N-1)
System.out.println(a[x]);
else
{ 
count = compare(a,x,x+1,count,N);
/* for(int y=x+1;y&lt;N;y++)
if(a[x]&gt;=a[y])
count++; */
if(count==(N-x-1))
System.out.print(a[x]);
leader(a,N,x+1);
}
}
static int compare(int []a,int x,int y,int count,int N)
{
if(y==N)
return count;
else
{
if(a[x]&gt;=a[y])
count ++;
return compare(a,x,y+1,count,N);
}
}
}

Error :

Runtime Error:
Runtime ErrorTime Limit Exceeded
Your program took more time than expected.Time Limit Exceeded
Expected Time Limit 3.00sec

答案1

得分: 0

一个问题(也是导致程序运行时间长的可能原因)是你的compare()方法在遇到较大值后并不会停止,因此很明显当前的元素不是领导者。相反,它会一直比较所有的值。
这使得你的代码对于一个大小为N的数组的运行时间复杂度为O(N^2)。

这个问题可以在O(N)的时间内解决。
从数组的右端开始,将最后一个元素视为领导者,并将其设为当前最大值。然后向左移动,检查当前元素是否大于等于最大值。如果是,则将其视为领导者,并将其设为最大值。继续直到达到数组的左端。

另外,你可能还可以通过用一个简单的for循环来替换你的递归toInts()方法,从而节省一些时间,用以将字符串转换为整数。

英文:

A problem (and the likely cause for the long time it takes) is that your compare() method doesn't stop once it encounters a larger value and it is therefore obvious that the current element is not a leader. Instead it will always compare all values.
This makes the runtime of your code O(N^2) for an array of size N.

This problem can be solved in O(N).
Start on the right end of the array and print the last element as leader and set it as the current maximum. Then go left and check if the current element is greater or equal than the maximum. If yes print it as a leader and set is as the maximum. Continue until you reach the left end of the array.

You can also probably save some time by replacing your recursive toInts() method with a simple for-loop to convert the strings.

huangapple
  • 本文由 发表于 2020年10月19日 20:07:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64427033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定