Straight forward but stupid solution in Java


  • 0
        public int[] findRightInterval(Interval[] intervals) {
            if(intervals.length == 0) return new int[0];
            int n = intervals.length;
            Map<Interval, Integer> map = new HashMap<Interval, Integer>();
            for(int i = 0; i < n; i ++){
                map.put(intervals[i], i);
            }
            
            Arrays.sort(intervals, new Comparator<Interval>(){
                @Override
                public int compare(Interval i1, Interval i2){
                    return i1.start - i2.start;
                }
            });
            int res[] = new int[n];
            Arrays.fill(res, -1);
            for(int i = 0; i < n; i ++){
                int j = i + 1;
                while(j < n && intervals[j].start < intervals[i].end){
                    j ++;
                }
                int idx1 = map.get(intervals[i]), idx2 = j < n ? map.get(intervals[j]) : -1;
                res[idx1] = idx2;
            }
            return res;
        }
    

Log in to reply
 

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