😕题目描述

😔分析

利用第二个数进行排序,得到如下这种状态。

  1. [[1,2],[2,5],[3,4][5,6]]
  2. -------------------------->
  3. [[1,2],[3,4],[2,5],[5,6]]

然后进行查找,当前第一个元素大于当前基准时则将该数对加入,并且基准变为新的基准。
即在找到3的时候,基准变为4。以此类推。

😏答案

type Pairs [][]int

func (p Pairs) Len() int {
    return len(p)
}

func (p Pairs) Less(i, j int) bool {
    return p[i][1] < p[j][1]
}

func (p Pairs) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
}
func findLongestChain(pairs [][]int) int {
    var temp Pairs
    temp = pairs
    sort.Sort(temp)

    cnt := 1
    lel := temp[0][1]

    for i, _ := range temp {
        if i == 0 {
            continue
        } else {
            if temp[i][0] > lel {
                cnt++
                lel = temp[i][1]
            }
        }
    }
    return cnt
}