LeetCode Mock Review 2021-4-11
今天的Mock属于很简单的那种,读题花费了大部分时间。15分钟轻松AC。
836. Rectangle Overlap
836. Rectangle Overlap
第一道题数学题,先判断两个矩形的坐标是否都正确。然后取其中一个作为参考基准,判断另一个矩形与其是否有重叠。要注意的是testcase里有的坐标并不是矩形而是一条线。第一次提交的时候被这个testcase害了。
class Solution {
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
if(rec1[0]>=rec1[2] || rec1[1] >= rec1[3] || rec2[0] >= rec2[2] || rec2[1] >= rec2[3])
return false;
if(rec2[0]>=rec1[2] || rec2[2] <= rec1[0] || rec2[1] >= rec1[3] || rec2[3] <= rec1[1]){
return false;
}else{
return true;
}
}
}
763. Partition Labels
763. Partition Labels
这道题是之前刷过的一道题,所以简单回忆了一下就写出来了。先遍历一遍字符串,用一个数组存储每个字母最后出现的位置。这个是用来判断分割位置的。然后从第头开始推进,使用start标记每次分割的首位置,使用end来记录每次分割的末位置。每遍历到一个字符,就检查它最后一次出现的位置,如果在当前end的位置之后,就更新end到这个字符最后一次出现的位置,否则就继续遍历。直到遍历到end位置时,说明可以分割了。将end-start +1装入结果List中,然后将start更新到下一个位置。遍历不用考虑最后的位置,因为遍历到字符串尾部时必定会分割一次。
class Solution {
public List<Integer> partitionLabels(String S) {
List<Integer> res = new ArrayList<>();
if(S == null || S.trim().equals("") || S.length() == 0) return res;
int start = 0, end = 0;
int[] last = new int[26];
Arrays.fill(last, -1);
for(int i = 0; i < S.length(); i++){
last[S.charAt(i) - 'a'] = i;
}
for(int i = 0; i < S.length(); i++){
char c = S.charAt(i);
end = Math.max(end, last[c-'a']);
if(i == end){
res.add(end-start + 1);
start = end + 1;
}
}
return res;
}
}
总结:这次mock非常轻松,出错的点在于没有考虑输入是极限情况时的判断,以及标记的初始赋值。继续加油!