-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterval.java
More file actions
77 lines (68 loc) · 1.7 KB
/
Interval.java
File metadata and controls
77 lines (68 loc) · 1.7 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package fr.sofiane.programme;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeSet;
import java.lang.Math;
public class Interval {
public static class TabInt implements Comparable<Object> {
int pEl;
int dEl;
public TabInt(int[] tab) {
super();
this.pEl = tab[0];
this.dEl= tab[1];
}
@Override
public int compareTo(Object o) {
TabInt e= (TabInt)o;
return pEl-e.pEl;
}
@Override
public String toString() {
return "TabInt [pEl=" + pEl + ", dEl=" + dEl + "]";
}
public int tailleInterval() {
return dEl-pEl;
}
}
public static ArrayList<TabInt> trieListe(ArrayList<TabInt>liste){
for(int i=0;i<liste.size()-1;i++) {
if(liste.get(i).dEl>=liste.get(i+1).pEl) {
liste.get(i).dEl=Math.max(liste.get(i).dEl,liste.get(i+1).dEl);
liste.remove(i+1);
}
}
for(int i=0;i<liste.size()-1;i++) {
if(liste.get(i).dEl>liste.get(i+1).pEl)
return trieListe(liste);
}
return liste;
}
public static int sumIntervals(int[][] intervals) {
if(intervals==null)
return 0;
else if(intervals.length==0)
return 0;
else if(intervals[0]==null || intervals[0].length==0)
return 0;
else {
HashSet<TabInt> hs = new HashSet<TabInt>();
for(int i=0;i<intervals.length;i++)
{
TabInt e=new TabInt(intervals[i]);
hs.add(e);
}
TreeSet<TabInt> trie=new TreeSet<TabInt>(hs);
ArrayList<TabInt> liste= new ArrayList<TabInt>(trie);
trieListe(liste);
int res=0;
for(TabInt e:liste)
res+=e.tailleInterval();
return res;
}
}
public static void main (String[]args) {
int[][] tab= {{1,2},{1,2},{1,5},{11,202}};
System.out.println(sumIntervals(tab));
}
}