用ACM模式模板刷hot100
面试手撕给的模板基础上写
给的模板一般是下面这样
把while内容删除(一般刷hot100题目输入不需要同时输入几组)
第一个方法里写处理输入输出
自己再写一个方法,就是力扣里的核心代码(加上static)
第一个处理输入输出的方法里面调用第二块的方法
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
while(in.hasNextInt()){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a+b);
}
}
}
答题模板
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
...
}
public static int[] method(int[] nums,int target){
...
}
}
举例“两数之和”
import java.util.*;
public class Main {
public static void main(String[] args) {
// 数据输入
Scanner in = new Scanner(System.in);
// 读取数组长度
int n = in.nextInt();
in.nextLine();
// 读取数组元素
int[] nums = new int[n];
String[] inputNums = in.nextLine().split(" ");
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(inputNums[i]);
}
// 读取目标值
int target = in.nextInt();
// 处理 输出
int[] result = twoSum(nums, target);
System.out.println(result[0] + " " + result[1]);
}
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
int[] res = new int[2];
for(int i = 0; i<nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[0] = map.get(temp);
res[1] = i;
}
map.put(nums[i], i);
}
return res;
}
}
还有一种写法是
第二块完整写力扣代码,第一段先实例化再调用
这个方法可以不用,记第一个就行
public class Main {
public static void main(String[] args) {
//1.数据输入
Scanner in = new Scanner(System.in);
//读数字
int numLen = in.nextInt();
int[] numArr = new int[numLen];
int i = 0;
while(in.hasNextInt() && i < numLen){
numArr[i] = in.nextInt();
i++;
}
//读字符串
int strLen = in.nextInt();
in.nextLine(); //数字到字符串要换行
String[] strArr = new String[strLen];
//或者 strArr[] = in.nextLine().split(" ");
int j = 0;
while(in.hasNextLine() && j < strLen){
strArr[j] = in.nextLine();
j++;
}
//2. 处理
Solution solution = new Solution();
String result = solution.process(numArr, strArr);
//3. 输出
System.out.println(result);
//四舍五入输出小数
String str = String.format("%.2f",3.555);
System.out.println(str);
}
}
//下面类似 LeetCode 的核心代码模式
class Solution {
public String process(int[] nums, String[] strs) {
StringBuilder sb = new StringBuilder();
sb.append(Arrays.toString(nums));
sb.append(" && ");
sb.append(Arrays.toString(strs));
return sb.toString();
}
}