Accepted Java Solution


  • 3
    V
    public class Solution {
        public boolean canAttendMeetings(Interval[] intervals) {
            Arrays.sort(intervals, new Comparator<Interval>(){
                @Override
                public int compare(Interval lhs, Interval rhs){
                    if (lhs.start == rhs.start) return 0;
                    return lhs.start > rhs.start ? 1 : -1;
                }
            });
    
            int firstEndTime = intervals[0].end;
            for (int i = 1; intervals.length > 1 && i < intervals.length; i++) {
                if (firstEndTime > intervals[i].start) return false;
                firstEndTime = intervals[i].end;
            }
            return true;
        }
    }

  • 0
    Y

    Idea is the same as yours. Below is my code:

    public class Solution {
    	public boolean canAttendMeetings(Interval[] intervals) {
    		Arrays.sort(intervals, new Comparator<Interval>(){
    			public int compare(Interval a, Interval b){
    				if(a.start==b.start) return 0;
    				return (a.start>b.start)?1:-1;
    			}
    		});
    		
    		if(intervals.length==1) return true;
    		
    		for(int i=0; i<intervals.length-1; i++) {
    			if(intervals[i].end>intervals[i+1].start)
    				return false;
    		}
    		return true;
    	}
    }

  • 0
    S

    in the compare method, you can only use one statement

    return lhs.start - rhs.start;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.