码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Maximum Length of Pair Chain

时间:2017-09-24 09:55:05      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:while   logs   链接   complex   use   pac   http   sele   ref   

原题链接在这里:https://leetcode.com/problems/maximum-length-of-pair-chain/description/

题目:

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: 2
Explanation: The longest chain is [1,2] -> [3,4]

Note:

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

题解:

按照pair的second number 排序pairs. 再iterate pairs, 若当前pair的second number 小于下个pair的first number, 计数sum++, 否则跳过下个pair.

Note: 用curEnd把当前的second number标记出来, 不要用pair[i][1], 否则 i 跳动时就不是当前pair的second number了.

Time Complexity: O(nlogn). n = pairs.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int findLongestChain(int[][] pairs) {
 3         if(pairs == null || pairs.length == 0){
 4             return 0;
 5         }
 6         
 7         int len = pairs.length;
 8         Arrays.sort(pairs, new Comparator<int []>(){
 9             public int compare(int [] a, int [] b){
10                 return a[1] - b[1];
11             }
12         });
13         
14         int i = 0;
15         int sum = 0;
16         while(i<len){
17             sum++;
18             int curEnd = pairs[i][1];
19             while(i+1<len && curEnd>=pairs[i+1][0]){
20                 i++;
21             }
22             i++;
23         }
24         return sum;
25     }
26 }

 

LeetCode Maximum Length of Pair Chain

标签:while   logs   链接   complex   use   pac   http   sele   ref   

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/7584319.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!