1.Java快读模板
我们以往使用的Scanner sc = new Scanner(System.in);
和String s = sc.nextLine();
在输入数据非常大的时候会变得很慢,增加程序运行时间,因此用字符缓冲流来代替,提高运行速度!
private static final BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
private static final PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
private static String Line() { String p = ""; try { p = bf.readLine(); } catch (IOException e) { e.printStackTrace(); } return p; }
public static void main(String[] args) { String inStr = Line(); pw.println(inStr); pw.flush(); }
|
2.二叉树处理模板
二叉树是最常见的数据结构之一,在处理输入的通常是一个数组要转化为二叉树,而输出的时候往往要将二叉树转化为数组。
下面是二叉树节点类+根据int类型数组生成二叉树+给定root打印二叉树值的代码模板
package leetcode.Binary_Trees;
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue;
public class TreeUtils {
public static String serialize(TreeNode root) { if(root == null) { return "[]"; } List<String> list = new ArrayList<>(); Queue<TreeNode> que = new LinkedList<>(); que.add(root); while(!que.isEmpty()) { TreeNode node = que.poll(); if(node != null) { list.add(node.val + ""); que.add(node.left); que.add(node.right); }else { list.add("null"); } } int flag = list.size() - 1; for (int i = list.size() - 1; i >= 0; i--) { if(!"null".equals(list.get(i))) { flag = i; break; } } StringBuilder sb = new StringBuilder("["); for (int i = 0; i <= flag; i++) { sb.append(list.get(i)).append(","); } return sb.deleteCharAt(sb.length() - 1).append("]").toString(); }
public static TreeNode deserialize(String data) { if("[]".equals(data)) { return null; } String[] strs = data.substring(1, data.length() - 1).split(","); int strsLen = strs.length; int i = 1; Queue<TreeNode> que = new LinkedList<>(); TreeNode root = new TreeNode(Integer.parseInt(strs[0])); que.add(root); while(!que.isEmpty()) { TreeNode node = que.poll(); if(i < strsLen && !"null".equals(strs[i])) { TreeNode left = new TreeNode(Integer.parseInt(strs[i])); node.left = left; que.add(left); } i++; if(i < strsLen && !"null".equals(strs[i])) { TreeNode right = new TreeNode(Integer.parseInt(strs[i])); node.right = right; que.add(right); } i++; } return root; } }
|
3.链表处理模板
链表是最简单的数据结构之一,下面给出链表节点类+根据int数组生成链表+给定head打印节点值代码模板
public class LinkListUtil { public static ListNode generateLinkList(int[] arr) { ListNode nex = null; for (int i = arr.length - 1; i >= 0; i--) { ListNode cur = new ListNode(arr[i]); cur.next = nex; nex = cur; } return nex; }
public static void printLinkList(ListNode head) { ListNode cur = head; List<Integer> list = new ArrayList<>(); while (cur != null) { list.add(cur.val); cur = cur.next; } System.out.println(list); } }
public class ListNode { int val; ListNode next;
ListNode() { }
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; } }
|