本科只用过C++和Python刷题,原因是感觉Java语言太冗长厚重。 最近尝试了下用Java刷题,总结一下输入输出
最基本的输入输出:
Scanner sc = new Scanner(System.in);//输入 util包下
String next = sc.next();
int x = sc.nextInt();
System.out.println();// 输出
System.out.print();
更快一些的输入输出:
注意引入 io包和 throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//输入
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));//输出
String[] firstline = br.readLine().split(" ");//注意是读取一行
int n=Integer.parseInt(firstline[0]);//转为整型
bw.newLine();//换行
bw.write(1+"");//输出也只能输出字符串,如果需要输出一个数字,则需要+""以转成字符串。
br.close();
bw.flush();// 刷新(需要刷新才能显示)
bw.close();
举例子: 154. 滑动窗口 https://www.acwing.com/problem/content/description/156/
标准输入输出
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] nums = new int[n];
for(int i = 0; i < n; i++){
nums[i] = sc.nextInt();
}
Deque<Integer> q = new LinkedList<>();
for(int i = 0; i < n; i++){
if(q.size() > 0 && i - q.peekFirst() >= k){
q.pollFirst();
}
while(q.size() > 0 && nums[i] <= nums[q.peekLast()]){
q.pollLast();
}
q.add(i);
if(i >= k - 1){
System.out.print(nums[q.peekFirst()] + " ");
}
}
System.out.println();
q.clear();
for(int i = 0; i < n; i++){
if(q.size() > 0 && i - q.peekFirst() >= k){
q.pollFirst();
}
while(q.size() > 0 && nums[i] >= nums[q.peekLast()]){
q.pollLast();
}
q.add(i);
if(i >= k - 1){
System.out.print(nums[q.peekFirst()] + " ");
}
}
}
}
更快一些的输入输出:
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] s0 = br.readLine().split(" ");
int n = Integer.parseInt(s0[0]);
int k = Integer.parseInt(s0[1]);
int[] nums = new int[n];
String[] s1 = br.readLine().split(" ");
for(int i = 0; i < n; i++){
nums[i] = Integer.parseInt(s1[i]);
}
Deque<Integer> q = new LinkedList<>();
for(int i = 0; i < n; i++){
if(q.size() > 0 && i - q.peekFirst() >= k){
q.pollFirst();
}
while(q.size() > 0 && nums[i] <= nums[q.peekLast()]){
q.pollLast();
}
q.add(i);
if(i >= k - 1){
bw.write(nums[q.peekFirst()] + " ");
}
}
bw.newLine();
q.clear();
for(int i = 0; i < n; i++){
if(q.size() > 0 && i - q.peekFirst() >= k){
q.pollFirst();
}
while(q.size() > 0 && nums[i] >= nums[q.peekLast()]){
q.pollLast();
}
q.add(i);
if(i >= k - 1){
bw.write(nums[q.peekFirst()] + " ");
}
}
bw.flush();
bw.close();
br.close();
}
}
Java.util.Scanner类是一个简单的文本扫描类,它可以解析基本数据类型和字符串,它本质上其实是使用正则表达式去读取不同的数据类型
Java.io.BufferedReader类为了能够高效的读取字符序列,从字符输入流和字符缓冲区读取文本
BufferedReader的缓冲区大小为8KB,Scanner的缓冲区大小为1KB
Scanner的平均耗时是BufferedReader的10倍左右