zoukankan      html  css  js  c++  java
  • 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.

    Example 1:

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

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    基本考虑到了,但是不严谨:首先要确定是坐标型n-1,还是序列型n吧

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    lambda:Arrays.sort(pairs, (a,b) -> (a[0] - b[0])); 名称,括号->括号

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. dp数组不能和题目给的数组搞混

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    基本考虑到了,但是不严谨:首先要确定是坐标型n-1,还是序列型n吧

    [复杂度]:Time complexity: O(n^2) Space complexity: O(n)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    class Solution {
        public int findLongestChain(int[][] pairs) {
            //corner case
            if (pairs == null || pairs.length == 0) return 0;
            
            //initialization: sort, fill the array with 1
            Arrays.sort(pairs, (a,b) -> (a[0] - b[0]));
            int[] dp = new int[pairs.length];
            Arrays.fill(dp, 1);
            
            //for loop for i and j
            for (int i = 0; i < pairs.length; i++) {
                for (int j = i + 1; j < pairs.length; j++) {
                    dp[j] = Math.max(dp[j], pairs[j][0] > pairs[i][1] ? dp[i] + 1: dp[i]);
                }
            }
            
            return dp[pairs.length - 1];
        }
    }
    View Code
  • 相关阅读:
    模板【洛谷P3368】 【模板】树状数组 2
    模板【洛谷P3812】 【模板】线性基
    Java面向对象-多态
    Java常用工具类
    Java常用工具类
    Java static关键字
    MyBatis对象关联查询demo (一对多,多对一)
    将Cmder添加到系统右键菜单中
    IDEA 创建JavaWeb应用打包并发布
    IDEA 调试与打包
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9418696.html
Copyright © 2011-2022 走看看