上海耀乘健康科技有限公司笔试-两道送分题
第一题:月历问题
1. 题目描述:
题目:给定year,month,dayOfWeek三个数,输出整个月的日历表 【这里需要注意没有日期的地方需要填空字符串】 例子: input: 2021,3,1 // 含义为2021年3月,3月的第一天为星期1 output: [1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28], [29, 30, 31, "", "", "" , ""] input: 2020,2,6 // 含义为2020年2月,2月的第一天为星期6 【注意该月有29天】 output: ["", "", "", "", "", 1, 2], [3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, ""]需要实现的功能就类似linux命令的`cal 2 2020`,
二月 2020
日 一 二 三 四 五 六
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29 2. 解法:
比较简单,注意闰年的判别为 逢4年一闰,逢100年不闰,逢400年一闰 就行,下面贴我的代码:
public class MyDate {
public static void main(String[] args) {
int year = 2020;
int month = 2;
int dayOfWeek = 6;
// -------------------- begin -------------------- //
ArrayList<ArrayList<String>> ans = new ArrayList<>();
int daysOfMonth;
switch (month) {
case 2:
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
daysOfMonth = 29;
} else {
daysOfMonth = 28;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
daysOfMonth = 31;
break;
default:
daysOfMonth = 30;
}
int k = 1;
ArrayList<String> firstWeek = new ArrayList<>(7);
for (int j = 1; j <= 7; ++j) {
if (j < dayOfWeek) {
firstWeek.add("");
} else {
firstWeek.add(k++ + "");
}
}
ans.add(firstWeek);
while (k <= daysOfMonth) {
ArrayList<String> week = new ArrayList<>(7);
for (int j = 1; j <= 7; ++j) {
if (k <= daysOfMonth) {
week.add(k++ + "");
} else {
week.add("");
}
}
ans.add(week);
}
System.out.println(ans);
// -------------------- end -------------------- //
}
} 第二题:找出数组中第一个缺失的数
本题与leetcode题 [41. 缺失的第一个正数 https://leetcode-cn.com/problems/first-missing-positive/ ] 差不多,不过少了几个限制条件,
题意大致为:给定一个数组,其中所有元素的范围都属于[0,n],现在需要你较低的时间复杂度找出第一个缺失的数是多少?
可以使用 两次遍历 + hash 的方法,时间复杂度是 o(n)
下面贴我的代码:
public class NotInSeq {
public static void main(String[] args) {
int[] input = {0, 1, 2, 4, 5, 6, 7};
// -------------------- begin -------------------- //
int n = input.length;
int[] hash = new int[n + 1];
for (int i = 0; i < n; ++i) {
hash[input[i]] = 1;
}
for (int i = 0; i <= n; ++i) {
if (hash[i] == 0) {
System.out.println(i);
return;
}
}
// -------------------- end -------------------- //
}
}
哔哩哔哩公司氛围 723人发布