# java 贪心算法（无重复区间）

### *************************

### *************************

class Interval implements Comparable<Interval> {

private Integer start;
private Integer end;

public Integer getStart() {
return start;
}

public void setStart(Integer start) {
this.start = start;
}

public Integer getEnd() {
return end;
}

public void setEnd(Integer end) {
this.end = end;
}

@Override
public int compareTo(Interval o) {
if (this.getEnd()<o.getEnd()){
return -1;
}

if (this.getEnd()>o.getEnd()){
return 1;
}

return this.getStart().compareTo(o.getStart());
}

@Override
public String toString() {
return "["+this.getStart()+","+this.getEnd()+"] ";
}
}

public class MyTest {

public static List<Interval> generate(int num){
Random random=new Random();

List<Interval> list=new ArrayList<>();
for (int i=0;i<num;i++){
Interval interval=new Interval();

int start=random.nextInt(100);
int end=start+random.nextInt(20)+1;
interval.setStart(start);
interval.setEnd(end);

}

return list;
}

public static void main(String[] args){
List<Interval> list=generate(10);
System.out.println("初始区间为：");
list.forEach(System.out::print);

Collections.sort(list);
System.out.println("\n\n区间排序后：");
list.forEach(System.out::print);

int count=0;
for (int i=0;i<list.size()-1;i++){
for (int j=i+1;j<list.size();){
if (list.get(i).getEnd()>list.get(j).getStart()){
list.remove(j);
count++;
}else {
j++;
}
}
}

System.out.println("\n\n移除的区间数为："+count);
System.out.println("移除后区间为：");
list.forEach(System.out::print);
}
}

[77,80] [86,88] [68,79] [93,113] [44,62] [28,31] [57,65] [32,49] [89,100] [66,67]

[28,31] [32,49] [44,62] [57,65] [66,67] [68,79] [77,80] [86,88] [89,100] [93,113]

[28,31] [32,49] [57,65] [66,67] [68,79] [86,88] [89,100]

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

o_瓜田李下_o

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
08-10 4753

03-21 264
01-12 1万+
02-08 2443
04-08 3724
08-01 8052
12-16 265