10.29 高途笔试 ak 2/2
第一题 判断链表是否是循环链表,是返回0,返回倒数第n个数字,越界返回-1
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
String[] str = in.nextLine().split(" -> ");
int m = in.nextInt();
boolean flag = false;
Set<String> set = new HashSet<>();
for (int i = 0; i < str.length; i++) {
if (set.contains(str[i])){
flag = true;
break;
}
if (flag==true) break;
set.add(str[i]);
}
if (m>str.length) System.out.println(-1);
if (flag == true) System.out.println(0);
System.out.println(str[str.length-m]);
}
}
}
第二题 题目:给出一堆数组区间,求出最大数与最小数之间没有被覆盖的区间 按序打印、
二维数组排序
import java.util.*;
public class Main2 {
//一个基本的贪心的算法分析
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//注意细节以及判断有无顺序的分析
List<Integer[]> set = new ArrayList<>();
// 注意 hasNext 和 hasNextLine 的区别
String[] str = in.nextLine().split(";");
System.out.println(str[0]);
int[][] m = new int[str.length][2];
for (int i = 0; i < str.length; i++) {
String[] res = str[i].split(",");
m[i][0] = Integer.parseInt(res[0]);
m[i][1] = Integer.parseInt(res[1]);
}
Arrays.sort(m, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0]==o2[0]){
return o1[1]-o2[1];
}
return o1[0]-o2[0];
}
});
for (int i = 0; i < str.length-1; i++) {
if (m[i][1]<m[i+1][0]){
set.add(new Integer[]{m[i][1],m[i+1][0]});
}
}
if (set.size()==0) System.out.println(-1);
else {
for (Integer[] i: set) {
System.out.println("["+i[0]+", "+i[1]+"]");
}
}
}
}
