Share my Java 29ms Sort and Binary Search Solution


  • 0
    M
    public int[] findRightInterval(Interval[] intervals) {
            Interval[] list = new Interval[intervals.length];
            for(int i=0; i<intervals.length; i++) {
                list[i] = new Interval(intervals[i].start, i);
            }
            Arrays.sort(list, new customComp());
            int[] result = new int[intervals.length];
            for(int i=0; i<intervals.length; i++) {
                Interval entry = new Interval(intervals[i].end, 0); 
                int index = Arrays.binarySearch(list, entry, new customComp());
                if(index<0) index = -index-1;
                if(index>=intervals.length) result[i] = -1;
                else result[i] = list[index].end;
            }
            return result;
        }
        
        private class customComp implements Comparator<Interval> {
            public int compare(Interval a, Interval b) {
                return a.start-b.start;
            }
        }
    

Log in to reply
 

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