Simple and Direct, not using binary search.


  • 0
    S
    public class FindRightInterval {
        public int[] findRightInterval(Interval[] intervals) {
        	if (intervals.length == 0 || intervals == null) {
        		return new int[0];
        	}
        	if (intervals.length == 1) {
        		return new int[] {-1};
        	}
        	int n = intervals.length;
        	int[] result = new int[n];
        	for (int i = 0; i < n; i++) {
        		Interval interval = intervals[i];
        		result[i] = findInterval(intervals, i);
        	}
    
        	return result;
        }
    
        public int findInterval(Interval[] intervals, int i) {
        	Interval interval = intervals[i];
        	int end = interval.end;
        	int minDiff = Integer.MAX_VALUE;
        	int minIndex = -1;
        	for (int j = 0; j < intervals.length; j++) {
        		if (j != i) {
        			int diff = intervals[j].start - end;
        			if (diff >= 0 && diff < minDiff) {
        				minDiff = diff;
        				minIndex = j;
        			}
        		}
        	}
    
        	return minIndex;
        }
    }
    

Log in to reply
 

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