Find Right Interval

2017-05-25  本文已影响20人  我叫胆小我喜欢小心

题目来源
给一堆intervals,然后让你求每一个interval右边的最小的interval。
我的做法是先排个序,然后搞个map来映射索引和start,因为题目说start是唯一的。然后二分搜索来确定这个索引。

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<int> findRightInterval(vector<Interval>& intervals) {
        map<int, int> maps;
        vector<Interval> intervals_copy(intervals);
        int n = intervals.size();
        for (int i=0; i<n; i++)
            maps[intervals[i].start] = i;
        auto cmp = [](const Interval& i1, const Interval& i2){ return i1.start < i2.start; };
        sort(intervals_copy.begin(), intervals_copy.end(), cmp);
        vector<int> res(n, -1);
        for (int i=0; i<n; i++) {
            int target = intervals[i].end;
            int l = 0, r = n - 1, mid = 0;
            if (intervals_copy[r].start < target)
                continue;
            while (l < r) {
                mid = (l + r) / 2;
                if (intervals_copy[mid].start == target) {
                    r = mid;
                    break;
                }
                else if (intervals_copy[mid].start < target)
                    l = mid + 1;
                else
                    r = mid;
            }
            res[i] = maps[intervals_copy[r].start];
        }
        return res;
    }
};

看了看讨论区,发现自己有点傻,不对,主要是STL的各种还不熟悉,不会利用,用了之后就特别简单简洁,代码如下:

class Solution {
public:
    vector<int> findRightInterval(vector<Interval>& intervals) {
        map<int, int> hash;
        vector<int> res;
        int n = intervals.size();
        for (int i = 0; i < n; ++i)
            hash[intervals[i].start] = i;
        for (auto in : intervals) {
            auto itr = hash.lower_bound(in.end);
            if (itr == hash.end()) res.push_back(-1);
            else res.push_back(itr->second);
        }
        return res;
    }
};
上一篇下一篇

猜你喜欢

热点阅读