Leetcode(W12):646.Maximum Length of Pair Chain

題目:

 You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
 Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.
 Given a set of pairs, find the length longest chain which can be formed. You needn’t use up all the given pairs. You can select pairs in any order.

Note:
 The number of given pairs will be in the range [1, 1000].

Example:

Input: [[1,2], [2,3], [3,4]]
Output: 2
Explanation: The longest chain is [1,2] -> [3,4]

思路:

  這道題的題意是:如果前面鏈對的末元素小於後鏈對的首元素,那麼這兩個鏈對就可以鏈起來,問最大能鏈多少個?
  我的思路是首先把這些鏈對按順序排列,因爲每個鏈對的首元素都小於末元素,所以可以按照每個鏈對的末元素大小來進行排列。然後把排列後的第一個鏈對作爲當前鏈對隊列尾,遍歷鏈對,找到第一個符合首元素大於位於當前隊列尾的鏈對末元素的鏈對,然後更新當前鏈對隊列尾以及隊列鏈對個數。

代碼:

class Solution {
public:
    int findLongestChain(vector<vector<int>>& pairs) {
        sort(pairs.begin(), pairs.end(), cmp);
        int count = 1;
        int now = 0;
        for (int i = 1; i < pairs.size(); i++) {
            if (pairs[now][1] < pairs[i][0]) {
                now = i;
                count++;
            }
        }
        return count;
    }

private:
    static bool cmp(vector<int>& a, vector<int>&b) {
        return a[1] < b[1];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章