Java binary search solution O(nlogn)


  • 0
    G
    public int[] findRightInterval(Interval[] intervals) {
        int[] res = new int[intervals.length];
        StartIndex[] array = new StartIndex[intervals.length];
        for(int i = 0; i < intervals.length; i++) {
            array[i] = new StartIndex(intervals[i].start, i);
        }
        
        Arrays.sort(array, new Comparator<StartIndex>() {
            @Override
            public int compare(StartIndex a, StartIndex b) {
                return a.start - b.start;
            }
        });
        
        for(int i = 0; i < intervals.length; i++) {
            int idx = find(array, intervals[i].end);
            res[i] = idx == intervals.length ? -1 : array[idx].index;
        }
        return res;
    }
    
    public int find(StartIndex[] array, int end) {
        int left = 0, right = array.length;
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(array[mid].start < end) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
    
    class StartIndex {
        int start;
        int index;
        public StartIndex(int start, int index) {
            this.start = start;
            this.index = index;
        }
    }

Log in to reply
 

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