拼多多笔试思路
拼多多第一题代码:
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
class sortArr {
public static void main(String[] args) {
//利用java里的优先队列来实现一个最大堆,最后把前n个poll出来即可
PriorityQueue<Integer> q = new PriorityQueue<Integer>(new Comparator<Integer>() {
@Override
//堆的比较逻辑
public int compare(Integer o1, Integer o2) {
if ((o1 & 1) == 0 && (o2 & 1) == 0){
return o2-o1;
}
if ((o1 & 1) == 1 && (o2 & 1) == 1){
return o2-o1;
}
if ((o1 & 1) == 0 && (o2 & 1) == 1){
return -1;
}
if ((o1 & 1) == 1 && (o2 & 1) == 0){
return 1;
}
return 0;
}
});
Scanner in = new Scanner(System.in);
String str = in.nextLine();
//处理输入
int i = str.length()-1;
for (;i >= 0; i--) {
if (str.charAt(i) == ';') {
break;
}
}
int n = Integer.valueOf(str.substring(i+1));
String nums = str.substring(0,i);
String[] numsArr = nums.split(",");
//入堆
for (int j = 0; j < numsArr.length; j++) {
q.add(Integer.valueOf(numsArr[j]));
}
String res = "";
for (int j = 0; j < n; j++) {
res += q.poll();
if (j != n-1) {
res += ",";
}
}
System.out.println(res);
}
}
第二题:
import java.util.Scanner;
class Puke {
static String res="";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 0; i < n; i++) {
String num1 = in.next();
String num2 = in.next();
res += "{\n";
dfs(num1,"",num2,"");
if (i!=n-1) res += "}\n";
else res += "}";
}
System.out.println(res);
}
//num1是自己手里目前有多少张牌,newStr是新序列里的所有拍,num2是男朋友的牌,step是每一步的操作
private static void dfs(String num1, String newStr, String num2,String step) {
//如果新序列和男朋友牌相等那么就不递归了
if (newStr.equals(num2)) {
res += step+"\n";
return;
}
//手里还有牌,那么递归三种结果,递归回来后要把step置回进行前一个状态
if (num1.length() != 0) {
char head = num1.charAt(0);
step += "d ";
dfs(num1.substring(1),newStr,num2,step);
step = step.substring(0,step.length()-2);
step += "l ";
dfs(num1.substring(1),head+newStr,num2,step);
step = step.substring(0,step.length()-2);
step += "r ";
dfs(num1.substring(1),newStr+head,num2,step);
step = step.substring(0,step.length()-2);
}
}
}
