[算法分析与设计] leetcode 每周一题: Find Right Interval

题目链接:https://leetcode.com/problems/find-right-interval/description/

题目大意:给定一组区间(i, j),找出每一个区间“右边”最近的区间的索引

思路:

将题目给的interval 组转化为带有索引的indexIntreval组, 然后排序,接着对每个区间,遍历其右边的区间比较

代码:

/**
 * 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:
    struct indexInterval {
        int start;
        int end;
        int index;
        indexInterval():indexInterval(-1,-1,-1){}
        indexInterval(int s, int e, int i): start(s), end(e), index(i) {}
    };

    bool static compare(indexInterval a, indexInterval b) {

        return a.start <= b.start;
    }

    vector<int> findRightInterval(vector<Interval>& intervals) {
        vector<indexInterval> localSet;
        int len = intervals.size();
        for(int i = 0; i < len; i++) {
            int start = intervals[i].start;
            int end = intervals[i].end;
            localSet.push_back(indexInterval(start, end, i));
            
        }
        sort(localSet.begin(), localSet.end(), compare);

        vector<int> result(len,-1);
        for(int i = 0; i < len; i++) {
            int target = -1;
            for(int j = i + 1; j < len; j++) {
                
                if(localSet[j].start >= localSet[i].end) {
                    target = localSet[j].index;
                    break;
                }
            }
            result[localSet[i].index] = target;
            // target = -1;
        }

        return result;
    }

};

猜你喜欢

转载自blog.csdn.net/liangtjsky/article/details/78588289