思路:
// @Title: 插入区间 (Insert Interval)
// @Author: qisiii
// @Date: 2024-05-21 22:20:29
// @Runtime: 2 ms
// @Memory: 43.8 MB
// @comment:
// @flag:
class Solution {
class Point {
int start;
int end;
public Point(int start, int end) {
this.start = start;
this.end = end;
}
}
public int[][] insert(int[][] intervals, int[] newInterval) {
List<Point> pointList = new ArrayList<>();
for (int i = 0; i < intervals.length; i++) {
int[] val = intervals[i];
pointList.add(new Point(val[0], val[1]));
}
pointList.add(new Point(newInterval[0],newInterval[1]));
pointList.sort((a, b) -> {
int compare = Integer.compare(a.start, b.start);
if (compare == 0) {
compare = Integer.compare(a.end, b.end);
}
return compare;
});
Point cur = pointList.get(0);
List<Point> result = new ArrayList<>();
result.add(cur);
for (int i = 1; i < pointList.size(); i++) {
Point p = pointList.get(i);
Point last = result.get(result.size() - 1);
if (p.start <= last.end) {
last.end = Math.max(p.end,last.end);
} else {
result.add(p);
}
}
int[][] res = new int[result.size()][2];
for (int i = 0; i < result.size(); i++) {
res[i] = new int[] { result.get(i).start, result.get(i).end };
}
return res;
}
}
+++ title = “插入区间 (Insert Interval)” draft = false +++
思路:
// @Title: 插入区间 (Insert Interval)
// @Author: qisiii
// @Date: 2024-05-21 22:10:56
// @Runtime: 2 ms
// @Memory: 43.9 MB
// @comment:
// @flag:
class Solution {
class Point {
int start;
int end;
public Point(int start, int end) {
this.start = start;
this.end = end;
}
}
public int[][] insert(int[][] intervals, int[] newInterval) {
List<Point> pointList = new ArrayList<>();
for (int i = 0; i < intervals.length; i++) {
int[] val = intervals[i];
pointList.add(new Point(val[0], val[1]));
}
pointList.add(new Point(newInterval[0],newInterval[1]));
pointList.sort((a, b) -> {
int compare = Integer.compare(a.start, b.start);
if (compare == 0) {
compare = Integer.compare(a.end, b.end);
}
return compare;
});
Point cur = pointList.get(0);
List<Point> result = new ArrayList<>();
result.add(cur);
for (int i = 1; i < pointList.size(); i++) {
Point p = pointList.get(i);
Point last = result.get(result.size() - 1);
if (p.start <= last.end) {
last.end = Math.max(p.end,last.end);
} else {
result.add(p);
}
}
int[][] res = new int[result.size()][2];
for (int i = 0; i < result.size(); i++) {
res[i] = new int[] { result.get(i).start, result.get(i).end };
}
return res;
}
}