436. Find Right Interval

这题没什么难的,就是建map记下来每个interval本来的序列号,然后对intervals排序。
这里练习了C++的sort sort(lst.begin(), last.end()).
const关键字,map里的 at vs [] 的区别。

C++ 版本(1/1/2020更新)

class Solution {
public:
    vector findRightInterval(vector>& intervals) {
        std::unordered_map mp;
        std::vector lst;
        for (int i = 0; i < intervals.size(); i++) {
            mp[intervals[i][0]] = i;
            lst.push_back(intervals[i][0]);
        }
        sort(lst.begin(), lst.end());
        vector ans;
        for (auto& interval : intervals) {
            ans.emplace_back(helper(lst, mp, interval[1]));
        }
        return ans;
    }

private:
    int helper(const vector& lst, const unordered_map& mp, int target) {
        int l = 0, r = lst.size() - 1;
        while (l < r) {
            int m = l + (r - l) / 2;
            if (lst[m] == target) return mp.at(target);
            else if (lst[m] < target) l = m + 1;
            else r = m;
        }
        if (lst[r] >= target) return mp.at(lst[r]);
        return -1;
    }
};

这个也是用binary search
不过这个代码有点长。得看看怎么优化

class Solution {
    public int[] findRightInterval(Interval[] intervals) {
        Tuple[] array = new Tuple[intervals.length];
        for (int i = 0; i < intervals.length; i++) {
            array[i] = new Tuple(intervals[i], i);
        }
        Arrays.sort(array, new Comparator(){
            public int compare(Tuple o1, Tuple o2) {
                if (o1.itv.start == o2.itv.start) return 0;
                return o1.itv.start < o2.itv.start ? -1 : 1;
            }
        });
        int[] ans = new int[intervals.length];
        for (int i = 0; i < intervals.length; i++) {
            ans[i] = binarySearch(array, intervals[i].end);
        }
        return ans;
    }
    private int binarySearch(Tuple[] array, int target) {
        int l = 0, r = array.length - 1;
        while (l < r ) {
            int m = l + (r - l) / 2;
            if (array[m].itv.start == target) return array[m].id;
            if (array[m].itv.start < target) {
                l = m + 1;
            } else {
                r = m;
            }
        }
        if (array[l].itv.start >= target) return array[l].id;
        return -1;
    }
}
class Tuple {
    Interval itv;
    int id; 
    public Tuple(Interval itv, int id) {
        this.itv = itv;
        this.id = id;
    }
}

你可能感兴趣的:(436. Find Right Interval)