Describe the Painting LeetCode solution in Java

1
class Solution {
2
// class for segments
3
class Seg {
4
int val, end;
5
int color;
6
boolean isStart;
7

8
public Seg(int val, int end, int color, boolean isStart) {
9
this.val = val;
10
this.end = end;
11
this.color = color;
12
this.isStart = isStart;
13
}
14

15
public String toString() {
16
return "[" + val + " " + end + " " + color + " " + isStart + "]";
17
}
18
}
19

20
public List<List<Long>> splitPainting(int[][] segments) {
21
List<List<Long>> res = new ArrayList();
22

23
List<Seg> list = new ArrayList();
24

25
// making a list of segments
26
for (int[] segment : segments) {
27
list.add(new Seg(segment[0], segment[1], segment[2], true));
28
list.add(new Seg(segment[1], segment[1], segment[2], false));
29
}
30

31
// Sorting the segments
32
Collections.sort(
33
list,
34
(a, b) -> {
35
return a.val - b.val;
36
});
37

38
// System.out.println(list);
39

40
// Iterating over list to combine the elements
41
for (Seg curr : list) {
42
int len = res.size();
43
if (curr.isStart) {
44
// if the segment is starting there could be three ways
45
if (res.size() > 0 && res.get(len - 1).get(0) == curr.val) {
46
// if starting point of two things is same
47
List<Long> temp = res.get(len - 1);
48
temp.set(1, Math.max(temp.get(1), curr.end));
49
temp.set(2, (long) (temp.get(2) + curr.color));
50
} else if (res.size() > 0 && res.get(len - 1).get(1) > curr.val) {
51
// if there is a start in between create a new segment of different color
52
List<Long> prev = res.get(len - 1);
53
prev.set(1, (long) curr.val);
54
List<Long> temp = new ArrayList();
55
temp.add((long) curr.val);
56
temp.add((long) curr.end);
57
temp.add((long) (prev.get(2) + curr.color));
58
res.add(temp);
59
} else {
60
// Add a new value if nothing is present in result
61
List<Long> temp = new ArrayList();
62
temp.add((long) curr.val);
63
temp.add((long) curr.end);
64
temp.add((long) curr.color);
65
res.add(temp);
66
}
67
} else {
68
if (res.size() > 0 && res.get(len - 1).get(0) == curr.val) {
69
// if ending point of 2 segments is same
70
Long prevColor = res.get(len - 1).get(2);
71
res.get(len - 1).set(2, (long) (prevColor - curr.color));
72
} else if (res.size() > 0 && res.get(len - 1).get(1) > curr.val) {
73
// if there is a ending in between create a new segment of different color
74
Long prevColor = res.get(len - 1).get(2);
75
Long prevEnd = res.get(len - 1).get(1);
76
res.get(len - 1).set(1, (long) curr.val);
77

78
List<Long> temp = new ArrayList();
79
temp.add((long) curr.val);
80
temp.add((long) prevEnd);
81
temp.add((long) (prevColor - curr.color));
82
res.add(temp);
83
}
84
}
85
// System.out.println(res+" "+curr);
86

87
}
88
// System.out.println(res);
89
return res;
90
}
91
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0