leetcode 435. Non-overlapping Intervals

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cainiaohudi/article/details/79975728

借鉴了别人的代码,写成java

package leetcode;

import java.util.Arrays;
import java.util.Comparator;

class Interval {
    int start;
    int end;
    Interval() { start = 0; end = 0; }
    Interval(int s, int e) { start = s; end = e; }
}

class myComparator implements Comparator<Interval> {
    public int compare(Interval a, Interval b) {
        return a.end - b.end;
    }
}


public class NonoverlappingIntervals {

    public static int eraseOverlapIntervals(Interval[] intervals) {
        if (intervals.length == 0)  return 0;
        Arrays.sort(intervals, new myComparator());
        float end = (float) (-1/0.0);
        int erased = 0;    
        for (Interval i:intervals){
            if (i.start >= end)
                end = i.end;
            else
                erased += 1;               
        }         
        return erased;
    }

    public static void main(String[] args) {

        Interval[] intervals = new Interval[3];
        Interval x = new Interval(1,3);
        Interval y = new Interval(3,5);
        Interval z = new Interval(5,6);
        Arrays.fill(intervals,0,1,x);
        Arrays.fill(intervals,1,2,y);
        Arrays.fill(intervals,2,3,z);
        System.out.println(eraseOverlapIntervals(intervals));
    }
}
阅读更多
换一批

没有更多推荐了,返回首页