You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.
Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.
An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.
基本就是用兩個for迴圈,
第一個用來遍歷[left,right]包含的數字;第二個針對該數字檢查是否包含在ranges內
public boolean isCovered(int[][] ranges, int left, int right) {
// 第一個
for (int i = left; i <= right; i++) {
// 做一個布林值檢查有沒有被涵蓋
boolean covered = false;
// 第二個
for (int[] range : ranges) {
int start = range[0];
int end = range[1];
// 如果一旦被涵蓋就不用再檢查其他區間
if (i >= start && i <= end) {
covered = true;
break;
}
}
if (!covered) {
return false;
}
}
// 如果所有數字都被涵蓋,返回true
return true;
}
丟去leetcode檢查答案
成功了,結束這回合!
後來有去看其他人的解法,幾乎都是大同小異的,
也許這已經是最簡單解了?