LeetCode 646 Maximum Length of Pair Chain (贪心)

来源:互联网 发布:php大数据搜索 编辑:程序博客网 时间:2024/06/06 12:26

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.

Example 1:

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

Note:

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

题目链接:https://leetcode.com/problems/maximum-length-of-pair-chain/description/

题目分析:经典的贪心问题,按照第二个数字对数组排序,然后按题意尽可能多的取即可,原因很简单,要保证后面尽可能多的取,那么前面也应该尽可能早的结束
class Solution {        public int findLongestChain(int[][] pairs) {        int n = pairs.length;        if (n == 1) {            return 1;        }        Arrays.sort(pairs, new Comparator<int[]>() {            public int compare(int[] o1, int[] o2) {                return o1[1] - o2[1];            }        });        int ans = 1, i = 1, r = pairs[0][1];        while (i < n) {            while (i < n && pairs[i][0] <= r) {                i ++;            }            if (i == n) {                break;            }            r = pairs[i][1];            ans ++;        }        return ans;    }}


阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 王朝霸域华雄 华雄是谁杀的 关公温酒斩华雄 关羽温酒斩华雄的片段 温酒斩华雄的故事 三国之我是华雄 三国华雄 梦三国华雄 潘凤 关云长温酒斩华雄 三国志战略版华雄 关云长温酒斩华雄古文及译文 关云长温酒斩华雄意思 三国杀online华雄 华雅 华青陆渊免费阅读 华静家园二手房 华韩 东方整形医院 青岛整形医院排名 青岛华韩整形美容医院 华韩整形 8989 华音 华韵 华韵上城 华顺驾校 华颂 华颂7 华颂软件 华领 华颐 华风 华风海城湾 华飞 龙应台儿子华飞现状 华飞小吃培训 龙应台的儿子华飞照片 华驰 华骏 华骏挂车