java代码 80分,两个MLE,求大佬优化方法
查看原帖
java代码 80分,两个MLE,求大佬优化方法
437005
xiaoqi666楼主2023/1/12 13:57

对java不熟悉,求大佬解决一下。-。-

java代码(80分):2和10测试点MLE 记录


import java.io.*;


public class Main {
	static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
	static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	static PrintWriter cout = new PrintWriter(bw);
	static StreamTokenizer st = new StreamTokenizer(buf);
	public static int nextInt() throws IOException {
		st.nextToken();
		return (int)st.nval;
	}
	public static long nextLong() throws IOException {
		st.nextToken();
		return (long)st.nval;
	}
	static int q[] = new int[1000010];
	static int a[] = new int[1000010];
	public static void main(String[] args) throws IOException {
		int n,k;
		n = nextInt();
		k = nextInt();
		for(int i = 0;i < n;i ++) a[i] = nextInt();
		int hh = 0,tt = -1;
		for(int i = 0;i < n;i  ++)
		{
			if(hh <= tt && i - k + 1 > q[hh]) hh ++;
			while(hh <= tt && a[q[tt]] >= a[i]) tt --;
			q[ ++ tt] = i;
			if(i >= k - 1) cout.print(a[q[hh]] + " ");
		}
		hh = 0; tt = -1;
		cout.println();
		for(int i = 0;i < n;i  ++)
		{
			if(hh <= tt && i - k + 1 > q[hh]) hh ++;
			while(hh <= tt && a[q[tt]] <= a[i]) tt --;
			q[ ++ tt] = i;
			if(i >= k - 1) cout.print(a[q[hh]] + " ");
		}
		
		cout.flush();
		
	}
}

一模一样的C++代码(100分):

#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int a[N],q[N];
int main()
{
	int n,k;
	cin >> n >> k;
	for(int i = 0;i < n;i ++) cin >> a[i];
	int hh = 0,tt = -1;
	for(int i = 0;i < n;i ++)
	{
		if(hh <= tt && i - k + 1 > q[hh]) hh ++;
		while(hh <= tt && a[q[tt]] >= a[i]) tt --;
		q[ ++tt ] = i ;
		if(i >= k -1) cout << a[q[hh]] << " ";
	}
	cout << endl;
	 hh = 0,tt = -1;
	for(int i = 0;i < n;i ++)
	{
		if(hh <= tt && i - k + 1 > q[hh]) hh ++;
		while(hh <= tt && a[q[tt]] <= a[i]) tt --;
		q[ ++tt ] = i ;
		if(i >= k -1) cout << a[q[hh]] << " ";
	}
	return 0;
 } 
2023/1/12 13:57
加载中...